首页 > 代码库 > KVO 与 KVC 区别
KVO 与 KVC 区别
还长时间 没来了 今天分享一下 个人总结的 KCO KVC 笔记:
(如有错误,请速速联系我 愿听你的建议!)
- KVO 主要用于监听属性属性改变
- KVC 主要用于对某一对象的成员变量赋值
[item addObserver:self forKeyPath:@"one" options:0 context:nil];
[item addObserver:self forKeyPath:@"Two" options:0 context:nil];
[item addObserver:self forKeyPath:@"Three" options:0 context:nil];
[item addObserver:self forKeyPath:@"Four" options:0 context:nil];
既然监听了 就必须实现系统的监听方法: (在这个方法中设置一些属性值)
/**
* 监听到某个对象的属性改变了,就会调用
*
* @param keyPath 属性名
* @param object 哪个对象的属性被改变
* @param change 属性发生的改变
*/
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
[self.item removeObserver:self forKeyPath:@"badgeValue"];
[self.item removeObserver:self forKeyPath:@"title”];
KVC:
[student setValue:@"one" forKey:@"name"];
[student setValue:[NSNumber numberWithInt:17] forKey:@"age"];
在设置一个标量值时,需要先将标量值包装成一个NSNumber或NSValue对象
NSArray *keys = [NSArray arrayWithObjects:@"name", @"age", nil];
NSDictionary *dict = [student dictionaryWithValuesForKeys:keys];
NSArray *keys = [NSArray arrayWithObjects:@"name", @"age", nil];
NSArray *values = [NSArray arrayWithObjects:@"One", [NSNumber numberWithInt:16], nil];
NSDictionary *dict = [NSDictionary dictionaryWithObjects:values forKeys:keys];
[student setValuesForKeysWithDictionary:dict];