KVC and KVO in IOS development, ioskvckvo
KVC: Key-Value Coding
KVO: Key-Value Observing
Person. m
@ Interface Person: NSObject {// This access modifier is used to indicate that even private member variables can be accessed and assigned @ private NSString * _ name through kvc ;} @ end @ implementation Person @ end
PersonObserve. m
@ Interface PersonObserve: NSObject @ end @ implementation PersonObserve-(void) observeValueForKeyPath :( NSString *) keyPath ofObject :( id) object change :( NSDictionary *) change context :( void *) context {Person * p = (Person *) object; // obtain the NSLog (@ "% @", [p valueForKey: keypath]) of the keyPath of the member variable using kvc;} @ end
Main. m
Int main (int argc, const char * argv []) {// observer class PersonObserve * po = [[PersonObserve alloc] init]; person * p = [[Person alloc] init]; // use kvo to increase the value of the member variable "name". The observer po // po will be executed when the value changes-(void) observeValueForKeyPath :( NSString *) keyPath ofObject :( id) object change :( NSDictionary *) change context :( void *) context method [p addObserver: po forKeyPath: @ "name" options: NSKeyValueObservingOptionNew context: nil]; // set the attribute value of the member variable "name" in kvc mode. // The starting observer executes the corresponding method [p setValue: @ "yangys" forKey: @ "name"]; // remove the observation of the Private member variable "name" [p removeObserver: po forKeyPath: @ "name"]; return 0 ;}
Result:
2015-03-02 20:57:52.487 KVC&KOC[843:24874] yangysProgram ended with exit code: 0