KVC 简介设值的一个工具,对于指向id的对象,像其内存存取值。这有点像java的反射;
存在如下一个对象,已知其属性name,可取值:
id p=[[Person alloc] init]; NSString *name=[p valueForKey:@"name"];
Book *book1=[[Book alloc] init]; book1.name=@"effctive c++"; Book *book2=[[Book alloc] init]; book2.name=@" more effctive c++"; Book *book3=[[Book alloc] init]; book3.name=@" most effctive c++"; NSArray *arr=@[book1,book2,book3]; NSLog(@"%@",[arr valueForKey:@"name"]);
KVO指的是设值过程中对其监听的过程,以实现对业务逻辑的校验
//创建一个被监视的对象 Book *book1=[[Book alloc] init]; //设置监听对象 BookObserve *observe=[[BookObserve alloc] init]; //对其存值的监听-这种方法用完后不需要移除监听器 [observe observeValueForKeyPath:@"name" ofObject:book1 change:nil context:@"sadsada"]; //对其存值的监听-02 [book1 addObserver:observe forKeyPath:@"name" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil]; book1.name=@" most effctive c++"; NSLog(@"%@",book1.name); //取消对其存值的监听-02 [book1 removeObserver:observe forKeyPath:@"name"];
只要在.m文件中实现如下方法即可监听:
#pragma mark keyPath:对象属性 object:对象 change:存取值保存的字典 -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { }
原文地址:http://blog.csdn.net/qq285016127/article/details/37545675