When invoking an object through KVC, such as: [Self valueforkey:@ "Somekey"], the program automatically attempts to parse the call in several different ways. First find whether the object with Somekey this method, if not found, will continue to find whether the object with Somekey this instance variable (iVar), if not found, the program will continue to attempt to invoke-(ID) Valueforundefinedkey: This method. If this method is not implemented, the program throws a Nsundefinedkeyexception exception error.
KVC is a mechanism for manipulating object properties indirectly through strings,
Access to an object property we can person.age or by KVC Way [person valueforkey:@ ' age ']
KeyPath is a property-chained access as person.address.street a bit like the Pojo ognl expression in java.
If the given string does not have an object property that accesses the Valueforundefinekey method, the default implementation is raise an exception, but you can override this method, and the same goes for SetValue.
Key Path Accounts.transactions.payee would return an array with all of the payee objects, for all the transactions, in all th E accounts.
Throws an exception when you set a non-object property to nil, but you can also override the method
KVO is an observer pattern that is implemented at the language framework level, when the attribute is modified by KVC, the Observer is actively notified
Example
Person class
@implementation person
@synthesize Name,age;
-(void) changename{
name=@ "ChangeName directly";
}
@end
The Personmonitor class monitors the Name property
@implementation Personmonitor
-(void) Observevalueforkeypath: (NSString *) keypath
Ofobject: (ID) object
Change: (nsdictionary *) change
Context: (void *) context
{
if ([KeyPath isequal:@ "name"]) {
NSLog (@ "Change happen, old:%@ new:%@", [Change Objectforkey:nskeyvaluechangeoldkey],[change Objectforkey: Nskeyvaluechangenewkey]);
}
}
@end
Test code
Person *p =[[person alloc] init];
Personmonitor *pm= [[Personmonitor alloc]init];
[P addobserver:pm forkeypath:@ "name" Options: (Nskeyvalueobservingoptionnew |
Nskeyvalueobservingoptionold) Context:nil];
NSLog (@ "P.name is%@", p.name);
[P setvalue:@ "name KVC" forkey:@ "name"];
NSLog (@ "p name Get by KVC is%@", [P valueforkey:@ "name"]);
p.name=@ "Name change by. Name=";
[P changename]; Can ' t be notify
Output
2011-07-03 16:35:57.406 cocoa[13970:903] P.name is name
2011-07-03 16:35:57.418 cocoa[13970:903] change happen, Old:name New:name KVC
2011-07-03 16:35:57.420 cocoa[13970:903] p name Get by KVC is name KVC
2011-07-03 16:35:57.421 cocoa[13970:903] change happen, Old:name KVC new:name change by. name=
The last modification is a direct modification, so no notification is generated.