键值监听,就是可以监听对象某个属性值的变化;
首先,在工程中,新建一个Person的类
@interface Person : NSObject @property (nonatomic, copy) NSString *name; @end
在viewController中引入头文件“Person”,开始测试KVO的使用
- (void)viewDidLoad { [super viewDidLoad]; Person *person = [[Person alloc] init]; person.name = @"珠珠"; [person addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:@"testKVO"]; person.name = @"小雅"; [person removeObserver:self forKeyPath:@"name"]; } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context { NSLog(@"keypaht=%@, object=%@, change=%@, context=%@", keyPath,object, change, context); //NSKeyValueChangeOldKey 可以用"old"来代替,但是获取的话,如果系统修改old为"Old"的话,那会获取不到,所以建议用NSKeyValueChangeOldKey NSLog(@"获取被修改前的值=%@", change[NSKeyValueChangeOldKey]); //NSKeyValueChangeNewKey 可以用"new"来代替,但是获取的话,如果系统修改new为"New"的话,那会获取不到,所以建议用NSKeyValueChangeNewKey NSLog(@"获取修改后的值=%@", change[NSKeyValueChangeNewKey]); }
运行程序,得出来的值如下: