Specific explanations for the use of Key-value Coding (KVC) in iOS

Source: Internet
Author: User

Kvc Key-value encoding is an informal protocol. It provides a mechanism to indirectly access the properties of an object.

Direct access to the object is achieved by invoking the method of the listener, and KVC does not need to invoke the setup and fetch methods of the listener. The ability to directly access the properties of an object.

Here are some ways to use KVC:

1. Assigning values to attributes

KVC provides the following methods for setting the value of a property by key-value pairs. Equivalent to the Set method in the accessor. Value is the name of the property to be set, key is a string, and the contents of the string are

-(void) SetValue: (ID) value Forkey: (NSString *) key;-(void) SetValue: (ID) value Forkeypath: (NSString *) KeyPath;

The following is a sample sample to explain the code implementation of the property assignment through the access and KVC.

If there is a name attribute in the Student class , the name is assigned directly in the following way:

Student *stu = [[Student alloc] init];stu.name = @ "jerehedu";

Assign a value to name by KVO:

Student *stu = [[Student alloc] init]; [Stu setvalue:@ "jerehedu" forkey:@ "name"];

If another attribute in the student class is the ClassInfo class object Stuclass, there is a Classno class number attribute in the ClassInfo class class. The following is a direct way to set the class number:

Stu.stuclass = [ClassInfo New];stu.stuclass.classno = 1;

Set the class number by KVC:

Stu.stuclass = [ClassInfo new]; [Stu setvalue:@ (1) forkeypath:@ "Stuclass.classno"];

When set by KeyPath, the path is represented by xx.xx;

Value is the OC object. Assume the base data type. Need to be boxed. That is, the wrapper is the OC object.

2. Get the value of the property

KVC provides a way to get the value of an object's property, which is equivalent to the Get method of the accessor, which is also a key-value pair when the value is taken.

-(ID) Valueforkey: (NSString *) key;-(ID) Valueforkeypath: (NSString *) KeyPath;

The following is a sample sample to explain the code implementation of the property value via the KVC and the accessor .

If you want to get The value of name in the student class. The name is evaluated directly in the following way:

NSString *name = stu.name;

The way to KVC values is:

NSString *name = [stu valueforkey:@ "name"];

take the class number directly from the student class using the accessor method:

int num = Stu.stuClass.classNo;

take the class number in the student category by KVC:

int num = [[Stu valueforkeypath:@ "Stuclass.classno"] intvalue];

The default fetch value is the OC object. If you want the basic data type, you need to do the unpacking.

3. Key cannot be found. Handling Exceptions

When using KVC. Assuming that the key value in the code does not exist, it throws an exception and can be overridden in the class by providing the following method to resolve the problem.

-(void) SetValue: (ID) value Forundefinedkey: (NSString *) key;

When key does not exist. This method is invoked on its own initiative and can be processed in this way.

4, KVC use method supplement

The KVC is easy to use and simplifies our code, allowing you to perform operations on the properties of an object, in addition to being able to directly access the property without using the method of the interview.

  For example, add a test test class that has a score fraction attribute and an array in the student class. The array holds the test information (test class object), which can be directly obtained by KVO the average scores, best scores, etc. of all exams stored in the array.

  Storing the exam array information via KVO:

        Nsmutablearray *ary = [Nsmutablearray array];        for (int i=0; i<5; i++) {            Test *test = [[Test alloc] init];            [Test setvalue:@ (100-10*i) forkey:@ "Score"];            [ary Addobject:test];        }    stu.testary = ary;

Output the test print information in the Student class:

NSLog (@ "show:testary =%@", [Self valueforkey:@ "testary"]);    NSLog (@ "Show:testAry.score =%@", [self.testary valueforkey:@ "score"]);    NSLog (@ "Show:testAry.score =%@", [self.testary valueforkeypath:@ "score"]);        NSLog (@ "show: Total Sumscore =%@" in the array, [Self.testary valueforkeypath:@ "@sum. Score"]);    NSLog (@ "Show2: Average score in array avgscore =%@", [self.testary valueforkeypath:@ "@avg. Score"]);    NSLog (@ "Show2: Maximum score in array maxscore =%@", [self.testary valueforkeypath:@ "@max. Score"]);    NSLog (@ "Show2: Minimum score in array minscore =%@", [self.testary valueforkeypath:@ "@min. Score"]);

Inquiries or technical exchanges. Please add the official QQ Group: (452379712)

Jerry Education
Source:http://blog.csdn.net/jerehedu/
This article belongs to Yantai Jerry Education Technology Co., Ltd. and CSDN co-owned, welcome reprint. However, this statement must be retained without the author's permission. And in the article page obvious location to the original link, otherwise reserves the right to pursue legal responsibility.

Specific explanations for the use of Key-value Coding (KVC) in iOS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.