iOS如何为NSMutableArray添加KVO

转自:https://www.jianshu.com/p/f9fa928173ae

首先,数组不能直接使用KVO使用监听。当我们想要使用KVO监听数组的状态时改变然后尽心操作时,我们需要进行一下几部。

1.KVO不能监听UIViewController中的数组。我们需要先创建一个模型,将数组添加值模型中。

@interface SelectedsArr : NSObject

@property (nonatomic, strong) NSMutableArray *selecteds;///<选中的选项集合

@end

2.建立观察者以及观察者对象

[self.selectedsArr addObserver:self forKeyPath:@"selecteds" options:NSKeyValueObservingOptionNew context:nil];

3.处理Key的变化

这里,很重要,当向模型中的可变数组添加新成员时,不能直接用[self.selectedsArr.selecteds addObject:]方法。而使用该用下面的方法

[[self.selectedsArr mutableArrayValueForKey:@"selecteds"] addObject:]];

4.在下面的方法添加监听到变化后要执行的语句

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void *)context{

}

5.移除监听

[self removeObserver:self forKeyPath:@"selecteds"];

猜你喜欢

转载自blog.csdn.net/lxlzy/article/details/82811476
今日推荐