1、类属性设置与创建
// KvoClass.h
@interface KvoClass : NSObject
@property(nonatomic, copy) NSString *name;
@end
// ViewController.m
@property(nonatomic, retain) KvoClass *kvoObject;
_kvoObject = [[KvoClass alloc] init];
2、KVO 添加
// 添加观察者
[_kvoObject addObserver:self
forKeyPath:@"name"
options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
context:@"nameChange"];
// 改变被观察的键对应的值
_kvoObject.name = @"xiao bai";
sleep(2);
_kvoObject.name = @"xiao hei";
3、KVO 回调
// 系统自带方法
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
if (context == @"nameChange") {
NSLog(@"name 值被改变 kind = %@, oldValue = %@, newValue = %@",
change[@"kind"], change[@"old"], change[@"new"]);
}
else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
4、KVO 移除
- (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath context:(nullable void *)context;
- (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath;
- (void)dealloc {
// 移除观察者
[_kvoObject removeObserver:self forKeyPath:@"name" context:@"nameChange"];
}