标签:
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://www.cnblogs.com/mengfanrong/p/5203734.html