問(wèn)題
如何監(jiān)聽(tīng)一個(gè)數(shù)組count的變化
解決方案
1、可以在改變數(shù)組個(gè)數(shù)時(shí),進(jìn)行相應(yīng)的處理,如果監(jiān)聽(tīng)的范圍不大的話,哪addObject 、removeObject方里處理要監(jiān)聽(tīng)的事件等
2、比較高效的做是:
[[self mutableArrayValueForKey:@"array"] addObject:@“ff”];
這樣改變數(shù)組時(shí)就會(huì)觸發(fā)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"];
}