KVO nsobject类实现NSKeyValueCoding / NSKeyValueObserving非正式协议
本质上定义了一套让我们去遵守和实现的方法 KVO的使用
KVO的使用
//添加监听
self.abook = [[Book alloc]init];
[_abook addObserver:self forKeyPath:@"price" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:nil];
//实现监听
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqual:@"price"]) {
NSLog(@"old price: %@",[change objectForKey:@"old"]);
NSLog(@"new price: %@",[change objectForKey:@"new"]);
}
}
-(void)dealloc
{
//移除监听
[_abook removeObserver:self forKeyPath:@"price"];
}
//触发监听
NSDictionary *newBookPropertiesDictionary=[NSDictionary dictionaryWithObjectsAndKeys:
@"book name",@"name",
@"20.5",@"price",nil];
[self.abook setValuesForKeysWithDictionary:newBookPropertiesDictionary];
[self.abook setValue:@"34.0" forKey:@"price"];
Demo 下载地址:https://github.com/caigee/iosdev_sample
下的KVOdemo
厚吾(http://blog.csdn.net/mangosnow)
本文遵循“署名-非商业用途-保持一致”创作公用协议