The KVO key-value observer mode is an important mechanism of cocoa similar to the notification mode. When the attributes of the observer change, the observer performs corresponding operations.
Create a new person class to inherit nsobject, add the name and age attributes, and then create a personobserver class to inherit nsobject at the same time
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
Method
The details are as follows:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{ if ([keyPath isEqualToString:kPathName]) { NSLog(@"old name:%@ \nnew name:%@", [change objectForKey:@"old"], [change objectForKey:@"new"]); //Do something what you want to do //... return; } [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];}
Use keypath to determine whether the property of our listener has changed. If yes, perform the corresponding operation.
Add an observer to an object:
Person *person = [[Person alloc] init]; [person setName:@"old name"]; PersonObserver *observer = [[PersonObserver alloc] init]; [person addObserver:observer forKeyPath:@"name" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil]; [person setName:@"new name"]; [person removeObserver:observer forKeyPath:@"name"];
Running effect:
2013-03-05 16:08:04.347 learnOcKVO[10980:11303] old name:old name new name:new name