- 使用way1 (最正常用法)
#import "NSObject+FBKVOController.h"
[self.KVOController observe:self.label keyPath:@"text" options:NSKeyValueObservingOptionNew block:^(id _Nullable observer, id _Nonnull object, NSDictionary<NSKeyValueChangeKey,id> * _Nonnull change) {
//weakSelf
weakSelf.count ++;
if (weakSelf.count == 1) {
NSLog(@"weakSelf:%@",weakSelf);
NSLog(@"label:%@",weakSelf.label);
}
}];
FBKVOController 方便之处在于,不需要在dealloc里调用
-(void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath
- 使用way2(当self observe self
时)
[self.KVOControllerNonRetaining observe:self keyPath:@"numStr" options:NSKeyValueObservingOptionNew block:^(id _Nullable observer, id _Nonnull object, NSDictionary<NSKeyValueChangeKey,id> * _Nonnull change) {
//weakSelf
NSLog(@"%@",weakSelf.numStr);
}];
- 这时,需要使用KVOControllerNonRetaining,否则出现retainCycle
- 这时,还需要手动调用
removeObserver:
... orself.KVOControllerNonRetaining unobserve:
...
具体原因可以看源码~
另外,这种self observe self
实在没有必要用kvo,直接在setter方法中处理即可嘛。

网友评论