KVO原理
原理很简单,就是重写了被观察属性的 set 方法
如果直接访问变量,是无法触发的。
那针对数组的话,通常我们只是调用addObject,或者removeObject,
但以上方法并不会触发set方法,也就不会触发KVO的。
那么,该如何实现对 NSMutableArray 的 KVO 呢?
官方为我们提供了这个方法
解决方案:
- (NSMutableArray *)mutableArrayValueForKey:(NSString *)key
举个例子:
@property (nonatomic, strong) NSMutableArray *lines;
对需要观察的属性进行注册
[self addObserver:self
forKeyPath:@"lines"
options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld
context:nil];
触发方法,增删操作,使用addObject,或者removeObject并不会触发KVO
[[self mutableArrayValueForKey:@"lines"] addObject:@"1"],
观察回调方法
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary<NSString *,id> *)change
context:(void *)context
{
if([keyPath isEqualToString:@"lines"]){
NSMutableArray * lines = [self mutableArrayValueForKey:@"lines"];
if (lines.count) {
//do sth
}else{
//do sth
}
}
}
网友评论