问题
如何监听一个数组count的变化
解决方案
1、可以在改变数组个数时,进行相应的处理,如果监听的范围不大的话,哪addObject 、removeObject方里处理要监听的事件等
2、比较高效的做是:
[[self mutableArrayValueForKey:@"array"] addObject:@“ff”];
这样改变数组时就会触发KVO了。
例子:
@interface Controller : UIViewController
@property (nonatomic, copy) NSString *name;
@property (nonatomic, strong) NSMutableArray *array;
@end
[self addObserver:self forKeyPath:@"array"
options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
context:NULL
];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
if ([keyPath isEqualToString:@"array"]) {
NSLog(@"%zd”,self.array.count);
}
}
改变演示
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[[self mutableArrayValueForKey:@"array"] addObject:@“fsfs”];
}
移除
- (void)dealloc {
[_model removeObserver:self forKeyPath:@"array"];
}