objective-c – 使用NSMutableArray的KVO
发布时间:2020-12-16 10:29:47 所属栏目:百科 来源:网络整理
导读:我的AppDelegate中有一个名为blocks的NSMutableArray属性. 每当一个对象被添加到这个数组时我想观察. 我读过其他帖子,但我不明白为什么这不起作用. 在我的app委托类中,我实现了 - (void)insertObject:(id)obj inBlocksAtIndex:(NSInteger)index{ [blocks ins
我的AppDelegate中有一个名为blocks的NSMutableArray属性.
每当一个对象被添加到这个数组时我想观察. 我读过其他帖子,但我不明白为什么这不起作用. 在我的app委托类中,我实现了 - (void)insertObject:(id)obj inBlocksAtIndex:(NSInteger)index { [blocks insertObject:obj atIndex:index]; } 在我的视图控制器的init方法中,我将一个观察者添加到我的AppDelegate引用中. boardModel = [[UIApplication sharedApplication] delegate]; [boardModel addObserver:self forKeyPath:@"blocks" options:0 context:NULL]; 在我的视图控制器的viewDidLoad方法中,我尝试调用我之前实现的KVO索引数组访问器, [boardModel insertObject:[[Block alloc] init] inBlocksAtIndex:0]; 然后我实现我的observeValueForKeyPath方法: - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if ([keyPath isEqualToString:@"blocks"]) { NSLog(@"ADDED"); } } 我已经尝试在observeValueForKeyPath中的if语句之前添加一个NSLog语句,似乎它永远不会被调用. 我也尝试了NSLogging [[boardModel blocks] count],它说计数为1(正在添加对象). 我肯定错过了什么. 解决方法
您正在观察app委托的blocks属性,而不是块数组本身.希望以下示例能够明确区分:
// This will fire KVO as you're changing the app delegate's `blocks` property. appDelegate.blocks = [NSMutableArray array]; // This will not fire KVO as the app delegate's `blocks` property still points // to the same object; from the app delegate's perspective,nothing's happened. [appDelegate.blocks addObject:@"Object"]; 如果您希望在块数组的内容发生更改时收到通知,请观察数组本身的属性 – 类似于count.更新代码: [boardModel.blocks addObserver:self forKeyPath:@"count" options:0 context:NULL]; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |