FBKVOController 使用

2018-04-15  本文已影响83人  wustzhy
- 使用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);
    }];

  1. 这时,需要使用KVOControllerNonRetaining,否则出现retainCycle
  2. 这时,还需要手动调用removeObserver:... or self.KVOControllerNonRetaining unobserve:...
    具体原因可以看源码~

另外,这种self observe self实在没有必要用kvo,直接在setter方法中处理即可嘛。

image.png
上一篇 下一篇

猜你喜欢

热点阅读