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 replicated Valueforundefinedkey: method, Handle-(void) SetValue: (ID) value Forkey: (NSString *) key;// When a class does not have a property named key, it is called to throw an exception, which can be replicated-(void) SetValue: (ID) value Forundefinedkey: (NSString *) Key: Method, which handles//keypath as the path to access the property, such as: @ " Person.name ", person is the property of the current class, 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]; }}
iOS Development-KVC