使用KVO观察数组的变化
model类为: 将监听的数组封装到model里,不能监听UIViewController里面的数组
注意!!!!!!不能这样[_model.modelArray addObject]方法,需要这样调用
[[_model mutableArrayValueForKey:@"modelArray"] addObject:str];
第一步:新建一个model(NSObject) ,内部设置一个需要观察的数组属性。
第二步:在VC中初始化Model---> self.dataSourceModel = [[y_dataSourceModelalloc] init];
第三步:添加观察者KVO
/**
* KVO 观察model中属性--- 数据源
*/
[self.dataSourceModel addObserver:self forKeyPath:@"dataSource"options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
第四步:实现观察的方法
#pragma mark -- KVO
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
if ([keyPath isEqualToString:@"dataSource"]) {
......
}
}
第五步:释放观察者
-(void)dealloc
{
if (self.dataSourceModel != nil) {
[self.dataSourceModel removeObserver:self forKeyPath:@"dataSource"];
}
}
本文标题:使用KVO观察数组的变化
本文链接:https://www.haomeiwen.com/subject/iulzettx.html
网友评论