KVO 索引值觀察者模式是cocoa的一個重要機制類似Notification模式。當被觀察者屬性發生改變時觀察者做相應的操作。
建立一個Person類繼承NSObject,添加name和age屬性,接著建一個PersonObserver類繼承於NSObject同時實現
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
方法
具體如下:
- (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];}
利用keyPath判斷是否是我們監聽的屬性發生了變化,如果是做相應的操作。
為對象添加觀察者:
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"];
運行效果:
2013-03-05 16:08:04.347 learnOcKVO[10980:11303] old name:old name new name:new name