IOS kvc and ioskvc

Source: Internet
Author: User
Tags notification center

IOS kvc and ioskvc

In my mind, kvc is used to modify the attribute values of instance variables.

Today, I met kvc for the second time to learn about it. I have read many blogs online and it seems that it does not suit my taste. I will extract some of them and summarize them myself;

Http://www.cnblogs.com/stoic/archive/2012/07/20/2601315.html

This blogger writes some application instances, which I like very much. He explains how to perform Code operations;

Http://blog.csdn.net/omegayy/article/details/7381301

This blogger is the main principle;

The following are some useful articles extracted from the two blogs;

Overview

KVC is short for KeyValue Coding. It is a mechanism that uses the string name (key) to define class attributes. Instead of using the Setter and Getter methods.

KVC is a key technology when KVO, Core Data, CocoaBindings, and AppleScript (Mac Support) are used.


How to Use KVC

The key methods are defined in: NSKeyValueCodingprotocol

KVC supports class objects and built-in basic data types.

Get value

ValueForKey: Specifies the name of the NSString attribute.

ValueForKeyPath: Specifies the path of the NSString attribute, in the form of xx. xx.

ValueForUndefinedKey. Its default implementation is to throw an exception. You can rewrite this function for error handling.

Modify Value

SetValue: forKey:

SetValue: forKeyPath:

SetValue: forUndefinedKey:

SetNilValueForKey: When nil is set for non-Class Object Attributes, an exception is thrown by default.

One-to-multiple link members

MutableArrayValueForKey: ordered one-to-multiple relationship member NSArray

MutableSetValueForKey: unordered one-to-multiple link Member NSSet


The following are some operation examples:

1. Use KVC

# Import <Foundation/Foundation. h> @ interface Student: NSObject {NSString * name;} @ end # import "Student. h "int main (int argc, const char * argv []) {@ autoreleasepool {Student * student = [[Student alloc] init] autorelease]; [student setValue: @ "Zhang San" forKey: @ "name"]; NSString * name = [student valueForKey: @ "name"]; NSLog (@ "student name: % @", name);} return 0 ;}
2. Key Path access attributes
# Import <Foundation/Foundation. h> @ interface Course: NSObject {NSString * CourseName;} @ end # import "Course. h "@ implementation Course @ end # import <Foundation/Foundation. h> @ class Course; @ interface Student: NSObject {NSString * name; Course * course;} @ end # import "Student. h "# import" Course. h "int main (int argc, const char * argv []) {@ autoreleasepool {Student * student = [[Student alloc] init] autorelease]; [student setValue: @ "Zhang San" forKey: @ "name"]; NSString * name = [student valueForKey: @ "name"]; NSLog (@ "student name: % @", name ); course * course = [[Course alloc] init] autorelease]; [course setValue: @ "文" forKey: @ "CourseName"]; [student setValue: course forKey: @ "course"]; NSString * courseName = [student valueForKeyPath: @ "course. courseName "]; NSLog (@" course name: % @ ", courseName); // you can save the value [student setValue: @" keypath: @ "course. courseName "]; courseName = [student valueForKeyPath: @" course. courseName "]; NSLog (@" Course name: % @ ", courseName);} return 0 ;}
3. Automatically encapsulate Basic Data Types
# Import <Foundation/Foundation. h> @ class Course; @ interface Student: NSObject {NSString * name; Course * course; NSInteger point ;}@ end # import "Student. h "# import" Course. h "int main (int argc, const char * argv []) {@ autoreleasepool {Student * student = [[Student alloc] init] autorelease]; [student setValue: @ "Zhang San" forKey: @ "name"]; NSString * name = [student valueForKey: @ "name"]; NSLog (@ "student name: % @", name ); course * course = [[Course alloc] init] autorelease]; [course setValue: @ "文" forKey: @ "CourseName"]; [student setValue: course forKey: @ "course"]; NSString * courseName = [student valueForKeyPath: @ "course. courseName "]; NSLog (@" course name: % @ ", courseName); // you can save the value [student setValue: @" keypath: @ "course. courseName "]; courseName = [student valueForKeyPath: @" course. courseName "]; NSLog (@" Course name: % @ ", courseName); [student setValue: @" 88 "forKeyPath: @" point "]; NSString * point = [student valueForKey: @ "point"]; NSLog (@ "score: % @", point);} return 0 ;}


4. Operation set
# Import <Foundation/Foundation. h> @ class Course; @ interface Student: NSObject {NSString * name; Course * course; NSInteger point; NSArray * otherStudent;} @ end # import "Student. h "# import" Course. h "int main (int argc, const char * argv []) {@ autoreleasepool {Student * student = [[Student alloc] init] autorelease]; [student setValue: @ "Zhang San" forKey: @ "name"]; NSString * name = [student valueForKey: @ "name"]; NSLog (@ "student name: % @", name ); [student setValue: @ "88" forKey: @ "point"]; NSString * point = [student valueForKey: @ "point"]; NSLog (@ "score: % @", point); Student * student1 = [[[Student alloc] init] autorelease]; Student * student2 = [[Student alloc] init] autorelease]; student * student3 = [[Student alloc] init] autorelease]; [student1 setValue: @ "65" forKey: @ "point"]; [student2 setValue: @ "77" forKey: @ "point"]; [student3 setValue: @ "99" forKey: @ "point"]; NSArray * array = [NSArray arrayWithObjects: student1, student2, student3, nil]; [student setValue: array forKey: @ "otherStudent"]; NSLog (@ "scores of other students % @", [student valueForKeyPath: @ "otherStudent. point "]); NSLog (@" % @ student in total ", [student valueForKeyPath: @" otherStudent. @ count "]); NSLog (@" top score: % @ ", [student valueForKeyPath: @" otherStudent.@max.point "]); NSLog (@" lowest score: % @", [student valueForKeyPath: @ "otherStudent.@min.point"]); NSLog (@ "average score: % @", [student valueForKeyPath: @ "otherStudent.@avg.point"]);} return 0 ;}

Implementation Details of KVC:

Search for Setter and Getter Methods

This part is important, so that you can understand how to obtain and set the class member values after calling KVC.

Search simple members

For example, the basic type member, single object type member: NSInteger, NSString * member.

A. setValue: forKey search method:

1. First, find the setter method for setting and modifying attributes.

If the @ property, @ synthsize is used for processing, because @ synthsize tells the compiler to automatically generate the setter: Format setter method, It will be searched directly in this case.

Note: The setting method refers to the method that assigns values to attributes.

2. the above setter method is not found. If the class method accessInstanceVariablesDirectly (this method returns whether to directly access the variable that is not generated as an accesser), YES is returned (Note: This is the class method implemented in NSKeyValueCodingCatogery, YES is returned by default ).

Then press _Name, _ IsName,Name, IsName. (Set the variable nameName)

3. If the value of the Set member is found, if setValue: forUndefinedKey: is not called :.

 

B. valueForKey: search method:

Set variable name to name

1. First, press getName,Name, IsNameTo find the getter method and call it directly. If it is a built-in value type such as bool or int, NSNumber is converted.

2. The above getter is not found. Look for countOf.Name, ObjectInNameAtIndex :,NameAtIndexes format.

If countOf <Key> and one of the other two methods are found, a collection proxy object that can respond to all NSArray methods is returned ). The NSArray message method sent to this proxy set (collection proxy object) takes countOfName, ObjectInNameAtIndex :,NameAtIndexes is called in the form of a combination of these methods. There is also an optional getName:Range: method.

3. You have not found the countOf.Name, EnumeratorOfName, MemberOfName: Format method.

If all three methods are found, a proxy set (collection proxy object) that can respond to all NSSet methods is returned ). The NSSet message method sent to this proxy set (collection proxy object) takes countOfName, EnumeratorOfName, MemberOfName: Called in combination.

4. Still not found, if the class method accessInstanceVariablesDirectly returns YES, then press _Name, _ IsName,Name, IsNameTo directly search for member names.

5. If no more information is found, call valueForUndefinedKey :.

 

2.3.2 search for ordered set members, such as NSMutableArray

MutableArrayValueForKey: The search method is as follows:

1. Search for insertObject: in <Key> AtIndex:, removeObjectFrom <Key> AtIndex: or insert <Key>: atIndexes, remove <Key> AtIndexes: Format method.

If at least one insert method and at least one remove method are found, a proxy set that can respond to all NSMutableArray methods is also returned. Then the NSMutableArray message method sent to this proxy set uses insertObject: in <Key> AtIndex:, removeObjectFrom <Key> AtIndex:, insert <Key>: atIndexes and remove <Key> AtIndexes: called in combination. There are also two optional interfaces: replaceObjectIn <Key> AtIndex: withObject:, replace <Key> AtIndexes: with <Key> :.

2. Otherwise, search for the set <Key>: Format method. If the method is found, the NSMutableArray sent to the proxy set will eventually call the set <Key>: method.

That is to say, after modifying the proxy set retrieved by mutableArrayValueForKey, use set <Key>: to assign a value again. This method is much less efficient, so we recommend that you implement the above method.

3. Otherwise, if the class method accessInstanceVariablesDirectly returns YES, search for the member name in the order of _ <key> and <key>. If it is found, the NSMutableArray message method sent is directly transferred to this member for processing.

4. If no result is found, call setValue: forUndefinedKey :.

 

NSMutableArray * mutablearray = [kvo mutableArrayValueForKey: @ "array"]; // kvo adds an array to the custom class to obtain the proxy of the array through this method, modify the array value in kvo accordingly. [mutablearray removeObject: @ "234"]; [mutablearray addObject: @ "345"];

2.3.3 search unordered set members, such as NSSet.

MutableSetValueForKey: The search method is as follows:

1. search for add <Key> Object:, remove <Key> Object: or add <Key>:, remove <Key>: Format method, if at least one insert method and at least one remove method are found, a proxy set that can respond to all NSMutableSet methods is returned. Then the NSMutableSet message method sent to this proxy set is used to add <Key> Object:, remove <Key> Object:, add <Key >:, remove <Key>: combined call. There are two optional interfaces: intersect <Key> and set <Key> :.

2. If the reciever is ManagedObejct, the search will not continue.

3. Otherwise, search for the set <Key>: Format method. If the method is found, the NSMutableSet sent to the proxy set will eventually call the set <Key>: method. That is to say, after modifying the proxy set retrieved by mutableSetValueForKey, use set <Key>: to assign a value again. This method is much less efficient, so we recommend that you implement the above method.

4. Otherwise, if the class method accessInstanceVariablesDirectly returns YES, search for the member name in the order of _ <key> and <key>. If it is found, the NSMutableSet message method sent is directly transferred to this member for processing.

5. If no result is found, call setValue: forUndefinedKey :.

 

KVC also provides the following functions

Check the correctness of the 2.4 Value

KVC provides an API for verifying the property value. It can be used to check whether the set value is correct, to replace an incorrect value, or to reject the setting of a new value and return the error cause.

Verification Methods

The format is as follows: validate <Key>: error:

For example:

-(BOOL)validateName:(id *)ioValue error:(NSError **)outError{    // The name must not be nil, and must be at least two characters long.    if ((*ioValue == nil) || ([(NSString *)*ioValue length] < 2]) {        if (outError != NULL) {            NSString *errorString = NSLocalizedStringFromTable(                    @"A Person's name must be at least two characters long", @"Person",                    @"validation: too short name error");            NSDictionary *userInfoDict =                [NSDictionary dictionaryWithObject:errorString                                            forKey:NSLocalizedDescriptionKey];            *outError = [[[NSError alloc] initWithDomain:PERSON_ERROR_DOMAIN                                                    code:PERSON_INVALID_NAME_CODE                                                userInfo:userInfoDict] autorelease];        }        return NO;    }    return YES;}


Call the verification method:

ValidateValue: forKey: error: by default, the system searches for the verification method in the format of validate <Key>: error:. If it is found, it is called. If it is not found, YES is returned by default.

Pay attention to the memory management issues.

 

2.5 Set Operations

The set operation is used by passing the valueForKeyPath: parameter. It must be used on the Set (for example, array). Otherwise, a runtime error occurs. The format is as follows:

Left keypath part: the object path to be operated.

Collectionoperator part: Use the @ symbol to determine the set operation used.

Rightkey path: Set operation attributes.

2.5.1 Data Operations

@ Avg: Average Value

@ Count: Total

@ Max: Maximum

@ Min: Minimum

@ Sum: Total

The usage is shown in the preceding example.

Make sure that the Operation attribute is Numeric; otherwise, the runtime is incorrect.

2.5.2 object operations

Array

@ DistinctUnionOfObjects: returns the array of values after deduplication of the specified attribute.

@ UnionOfObjects: returns the array of the value of the specified attribute.

The attribute value cannot be blank; otherwise, an exception occurs.

2.5.3 Array Operations

Array Conditions

@ DistinctUnionOfArrays: returns the array of values after deduplication of the specified attribute.

@ UnionOfArrays: returns the array of the value of the specified attribute.

@ DistinctUnionOfSets: Same as above, but the returned value is NSSet.

 

Sample Code:

 

2.6 efficiency problems

It is a little less efficient than directly accessing KVC, so it is used only when you need the scalability it provides.


The following excerpt will show us why kvc is used:


. KVO is based on KVC. Some listeners cannot be listened to without KVC operations.
2. If Core Data is used, KVC must be used for value access. (Otherwise you will find various problems)
The main application scenario is collaboration with KVO and Core Data.

This unified interface that directly accesses the member attributes of objects in ObjC through strings can be used to execute or obtain program execution information by an external script control program.
It is also useful to access private members in the binary library through KVC.
Normal development does not and does not need to be used too much.

What is the prospect of learning ios? How can I learn ios well?

China's most authoritative "iOS high-paying employment course system"
China's most professional and free OC language video tutorial
China's first public "Real iOS training video"
Qian Feng's mission is to "do not boast, do not make false, and do education with a steadfast and practical conscience". Our goal is to solve the employment problem of College Students and deliver iOS development talents to enterprises. The "OC language video tutorial-the new version of 2013" was introduced here. It was taught by teacher Ouyang, a gold medal Lecturer in qianfeng. It provides the most professional teaching videos for fans interested in the iOS industry, lead them to the door of iOS!
Qian Feng gold lecturer Ouyang instructor introduction:
First person in iOS teaching video in China, leader in iOS teaching in China, master of Tsinghua University, former Technical Director of FSMLabs in China, 10 years of software development experience, 8 years of teaching experience, over 3 years of development experience in iOS and Android, responsible for the upgrade, transplantation and maintenance of the real-time RTLinux operating system for the development of ARM processors.
Objective-C is an object-oriented programming language for C extension, while Objective-C is used for iOS development. This topic provides a more systematic explanation of some key points in Objective-C, including object-oriented concepts, basic syntax, relationships between classes and objects, class encapsulation, constructor, self pointer, point syntax, Category syntax, basic data structure (NSString, NSArray, NSDictionary, NSNumber, NSSet, NSValue, NSData), inheritance (basic concepts, rewriting, virtual methods), memory management (Golden Rule, retain point syntax, MyArray, AutoreleasePool, shallow copy details, deep copy details ,), design mode (Singleton design mode, Singleton writing method, notification center, Blocks syntax, KVO, KVC), file operations (NSManager, NSFIleHandle, archive), and so on.

You can send a video tutorial on infinite interconnection iOS development: 92kvc classroom exercises-seeds of Chen Wei mov or download links?

Infinite interconnection iOS development video tutorial: 9.2.kvc classroom exercises-Chen Wei. mov seeds:
Thunder: // combined + R6KeG6aKR5pWZ56iL77yaOS4yLmt2Y + ivvuWggue7g + Signature =
Copy link download

Related Article

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.