带有 NSMutableArray 的 KVO [英] KVO With NSMutableArray

查看:45
本文介绍了带有 NSMutableArray 的 KVO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 AppDelegate 中有一个名为 blocks 的 NSMutableArray 属性.每当将对象添加到此数组时,我都想观察.我读过其他帖子,但我不明白为什么这不起作用.

I have a NSMutableArray property in my AppDelegate called blocks. I would like to observe whenever an object is added to this array. I've read other posts, but I can't understand why this isn't working.

在我的应用委托类中,我实现了

In my app delegate class, I implement

- (void)insertObject:(id)obj inBlocksAtIndex:(NSInteger)index
{
    [blocks insertObject:obj atIndex:index];
}

在我的视图控制器的 init 方法中,我将一个观察者添加到我的 AppDelegate 引用中.

In my view controller's init method, I add an observer to my AppDelegate reference.

boardModel = [[UIApplication sharedApplication] delegate];
[boardModel addObserver:self forKeyPath:@"blocks" options:0 context:NULL];

在我的视图控制器的 viewDidLoad 方法中,我尝试调用我之前实现的 KVO 索引数组访问器,

In my view controller's viewDidLoad method, I try invoking the KVO Indexed array accessor I implemented previously,

[boardModel insertObject:[[Block alloc] init] inBlocksAtIndex:0];

然后我实现了我的 observeValueForKeyPath 方法:

Then I implement my observeValueForKeyPath method:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"blocks"])
    {
        NSLog(@"ADDED");
    }
}

我已经尝试在observeValueForKeyPath 中的if 语句之前添加一个NSLog 语句,但它似乎从未被调用过.

I've tried adding an NSLog statement before the if statement in observeValueForKeyPath, and it seems as if it's never being called.

我也试过 NSLogging [[boardModel blocks] count],它说计数是 1(正在添加对象).

I've also tried NSLogging [[boardModel blocks] count], and it says the count is 1 (the object is being added).

我一定是遗漏了什么.

推荐答案

您正在观察应用程序委托的 blocks 属性,而不是 blocks 数组本身.希望下面的例子能清楚地说明区别:

You're observing the blocks property of the app delegate, not the blocks array itself. Hopefully the following example will make the difference clear:

// 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"];

如果您想在 blocks 数组的内容更改时收到通知,请观察数组本身的一个属性 - 类似于 count.更新您的代码:

If you want to be notified when the contents of the blocks array changes, observe a property on the array itself—something like count. Updating your code:

[boardModel.blocks addObserver:self forKeyPath:@"count" options:0 context:NULL];

这篇关于带有 NSMutableArray 的 KVO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆