1. What is KVC
Kvc--key-value coding, Health value code
Method that can directly access the value of an object property via key
2. Usage Scenarios
KVC is primarily intended to make the code more concise.
More is used in the background data parsing, and access to some of the properties of the Setter,getter method
3. Code parsing:
Definitions are in NSKeyValueCoding.h.
The main two methods:
// key is the property name of the current class -(ID) Valueforkey: (NSString *) key; // when a class does not have a property named key, it calls the throw exception, which can be Valueforundefinedkey: method, Handle -(void) SetValue: (ID) value Forkey: ( NSString *) key; // when a class does not have a property named key, it calls the throw exception, which can be replicated-(void) SetValue: (ID) value Forundefinedkey: (NSString *) Key: method, for processing // KeyPath is the path to the property, such as: @ "Person.name", the person is the property of the current class, and name is a property name of the People class -(ID) Valueforkeypath: (NSString * ) KeyPath; -(void) SetValue: (Nsvalue *) value Forkeypath: (NSString *) KeyPath;
Exception handling
-(ID) Valueforundefinedkey: (NSString *) key; -(void) SetValue: (ID) value Forundefinedkey: (NSString *) key
code example:
@interface Viewcontroller () @property (nonatomic, weak) NSString*viewstring, @end @implementation viewcontroller- (void) viewdidload {[Super viewdidload]; NSLog (@"----[%@]", [Self Valueforkey:@"viewstring"]); NSLog (@"----[%@]", [Self Valueforkey:@"Viewarray"]); [Self SetValue:@"testforviewstring"Forkey:@"viewstring"]; [Self SetValue:@"1"Forkey:@"Viewarray"]; }- (void) SetValue: (ID) value Forundefinedkey: (NSString *) Key {NSLog (@""WARNING"!!!!!! ---undefined--key[%@]--!!!!!!", key);}-(ID) Valueforundefinedkey: (NSString *) Key {if([Key isequaltostring:@"Viewarray"]) { return @"AAAA"; } Else { return[Super Valueforundefinedkey:key]; }}
Implementation principle
Reference Http://www.tuicool.com/articles/M7vQRj
Thank you for this article, written in very detailed
But there is a question:
Although these methods are generally not called or used, but I tried, the system did not call these methods, but directly went to the
-(ID) Valueforundefinedkey: (NSString *) key
iOS Development-KVC