KVC&KVO
2014-04-21 15:03
190 查看
ios讨论群1群:135718460
KVC
1.KVC直接修改某个对象的某个属性
[stu setValue:@"MIKE" forKey:@"name"];
[stu setValue:@10 forKey:@"age"];
2.KVC也可以批量设置某个对象的所有属性
[stu setValuesForKeysWithDictionary:@{@"age": @10,@"name":@"rose"}];
3.批量获取对象的属性
NSDictionary *dict = [stu dictionaryWithValuesForKeys:@[@"name",@"age"]];
4.使用键值路径间接修改对象的属性值
stu.book = [[Book alloc] init];
[stu setValue:@1.22 forKeyPath:@"book.price"];
5.通过KeyPath来获取数组内所有对象的相同属性
NSArray *array = @[stu,stu1,stu2];
NSArray *names = [array valueForKeyPath:@"name"];
6.通过keyPath来计算所有书的价格
stu.books = @[[Book bookWithPrice:2.2],[Book bookWithPrice:2.1],[Book bookWithPrice:10]];
int sum = [[stu valueForKeyPath:@"books.@sum.price"] intValue];
所有用key的地方都可以用keyPath
=======================================KVO=======================================
KVO是监听对象属性的改变
//通过KVO来监听stu的name属性的变化
[stu addObserver:observer forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:nil];
//属性改变后,会调用监听者的方法,并把一系列参数发送过来
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
NSLog(@"%@",keyPath);
NSLog(@"%@",object);
NSLog(@"%@",change[@"new"]);
}
KVC
1.KVC直接修改某个对象的某个属性
[stu setValue:@"MIKE" forKey:@"name"];
[stu setValue:@10 forKey:@"age"];
2.KVC也可以批量设置某个对象的所有属性
[stu setValuesForKeysWithDictionary:@{@"age": @10,@"name":@"rose"}];
3.批量获取对象的属性
NSDictionary *dict = [stu dictionaryWithValuesForKeys:@[@"name",@"age"]];
4.使用键值路径间接修改对象的属性值
stu.book = [[Book alloc] init];
[stu setValue:@1.22 forKeyPath:@"book.price"];
5.通过KeyPath来获取数组内所有对象的相同属性
NSArray *array = @[stu,stu1,stu2];
NSArray *names = [array valueForKeyPath:@"name"];
6.通过keyPath来计算所有书的价格
stu.books = @[[Book bookWithPrice:2.2],[Book bookWithPrice:2.1],[Book bookWithPrice:10]];
int sum = [[stu valueForKeyPath:@"books.@sum.price"] intValue];
所有用key的地方都可以用keyPath
=======================================KVO=======================================
KVO是监听对象属性的改变
//通过KVO来监听stu的name属性的变化
[stu addObserver:observer forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:nil];
//属性改变后,会调用监听者的方法,并把一系列参数发送过来
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
NSLog(@"%@",keyPath);
NSLog(@"%@",object);
NSLog(@"%@",change[@"new"]);
}
相关文章推荐
- 马上着手开发 iOS 应用程序 至 读后笔记
- IOS 如何选择delegate、notification、KVO?
- KVC
- KVO/KVC
- KVO/KVC系列之一——什么是KVC
- KVO/KVC系列之二——KVC编程
- kvc与kvo
- 【IOS】KVC(Key - value coding 机制) & KVO(键值观察)
- Objective-C语法之KVO的使用
- Objective-C语法之KVC的使用
- IOS KVC 机制
- IOS KVO 机制
- IOS开发(39)之KVC KVO KVB
- iOS中KVC与KVO的应用解析
- 键值监听KVO
- KVC setvalue:forkey与setvalue:forkeypath的区别
- 一个简单的KVO例子
- easyui修改源码实现combobox的真正模糊查询
- UIDynamic的基本使用
- 核心动画