文章目录
  1. 1. 索引

添加监控

1
[self addObserver:self forKeyPath:@"dealArr" options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionInitial) context:xxcontext];

监控回调

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{

if (context == xxcontext) {
if ([keyPath isEqualToString:@"dealArr"]) {
NSNumber *kind = change[NSKeyValueChangeKindKey];
NSArray *students = change[NSKeyValueChangeNewKey];
NSArray *oldStudent = change[NSKeyValueChangeOldKey];
NSIndexSet *changedIndexs = change[NSKeyValueChangeIndexesKey];

if ([kind isEqual: @1]) {
NSLog(@"数组初始化OK");
}else if ([kind isEqual: @2]){
NSLog(@"数组数量正在增加--目前数量%lu",self.dealArr.count);
}else if ([kind isEqual: @3]){
NSLog(@"数组数量正在减少 --目前数量%lu",self.dealArr.count);
}
}
} else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}

修改

1
2
3
4
5
6
7
8
//获取
NSMutableArray * s = [self mutableArrayValueForKey:NSStringFromSelector(@selector(dealArr))];
NSMutableArray * a = [uploads nsArray];
//插入 如此插入只会回调一次方法
NSIndexSet * indexes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(s.count, a.count)];
[s insertObjects:a atIndexes:indexes];
//删除也是
[s removeObjectsInArray:a];

索引

iOS如何为NSMutableArray添加KVO
NSKeyValueCoding Protocol Reference

文章目录
  1. 1. 索引