本人录制技术视频地址:https://edu.csdn.net/lecturer/1899 欢迎观看。
1.概述
KVO,即:Key-Value Observing,它提供一种机制,当指定的对象的属性被修改后,则对象就会接受到通知。简单的说就是每次指定的被观察的对象的属性被修改后,KVO就会自动通知相应的观察者了。
2.使用方法
系统框架已经支持KVO,所以程序员在使用的时候非常简单。
1. 注册,指定被观察者的属性,
2. 实现回调方法
3. 举例说明
Step One: 定义一个Person对象,并且拥有一个name属性
@interface Person : NSObject
@property(nonatomic,copy)NSString *name;
@end
PersonObserver.h文件
@interface PersonObserver : NSObject
@end
PersonObserver.m文件@implementation PersonObserver
// 回调方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
NSLog(@"%@-%@",keyPath,context);
[change enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSLog(@"%@,%@",key,obj);
}];
}
@end
int main(int argc, const char * argv[])
{
@autoreleasepool {
Person *p = [[Person alloc] init];
// 这一句执行完毕后,不会触发回调
p.name = @"Jason";
// 注册观察者observer
PersonObserver *observer = [[PersonObserver alloc] init];
[p addObserver:observer forKeyPath:@"name" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionNew context:@"Temp"];
// 属性发生了改变,会回调- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
p.name = @"Rose";
}
return 0;
}
4.总结说明