KVC&KVO

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:@"[email protected]"] 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"]);
}

你可能感兴趣的:(VC)