KVO - 观察自定义属性值
1 . 声明属性&注册监听
{ BOOL isOk; }
[self addObserver:self forKeyPath:@"isOk" options:0 context:nil];
2 .改变属性值
[self willChangeValueForKey:@"isOk"];
// 只有自己去定义时才需要如此设置
isOk = isOk?NO:YES;
[self didChangeValueForKey:@"isOk"];
3 . 监听值改变
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
if ([keyPath isEqualToString:@"isOk"]) {
NSLog(@"%d currentThread:%f",isOk,[NSThread currentThread]);
} else { // 一定要调用
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}