objective-c - KVO nsmutablearray 删除对象通知

标签 objective-c cocoa-touch

我有一个带有nsmutablearray的单例类

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
{
    NSLog(@"Received notification: keyPath:%@ ofObject:%@ change:%@",
          keyPath, object, change);

    //[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];

}
//array accessors
- (void)insertNewObject:(id)object
{
    [self willChangeValueForKey:@"heldJoins"];
    [heldJoins addObject:object];
    [self didChangeValueForKey:@"heldJoins"];
}
- (void)removeObject:(id)object
{
    [self willChangeValueForKey:@"heldJoins"];
    [heldJoins removeObject:object];
    [self didChangeValueForKey:@"heldJoins"];
}

我“观察”另一个类对此数组所做的更改 我的 Root View Controller

    [CCV addObserver:self forKeyPath:@"heldJoins" options:NSKeyValueChangeOldKey||NSKeyValueChangeNewKey context:NULL];

}    
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
    {    
        NSLog(@"Received notification: keyPath:%@ ofObject:%@ change:%@",keyPath, object, [change allKeys]);
    }

这有效,当删除或添加对象时我会收到通知 但是我无法弄清楚(也许不可能)如何查看已删除或添加的对象(主要需要删除时未添加的对象)

我知道NSDictionary变量Change应该有我的对象,但它所拥有的只是一个键“种类”,它总是等于1,因为总是对对象进行1次更改数组。

nsmutablearray 填充了数字 500,100,300 因此,当其中一个数字被删除时,我想知道在我的观察者类中删除了哪个数字 我该怎么做?

应答代码:

[CCV addObserver:self forKeyPath:@"heldJoins" options: NSKeyValueObservingOptionOld ||NSKeyValueChangeNewKey context:NULL];

NSLog(@"Received notification: keyPath:%@ ofObject:%@ change:%@",keyPath, object, [change valueForKey:@"new"]);

最佳答案

听起来您在添加观察者时没有指定 NSKeyValueObservingOptionOld。

关于objective-c - KVO nsmutablearray 删除对象通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7958774/

相关文章:

objective-c - 在资源中保存 URL

objective-c - 如何关闭 NSOpenPanel

ios - 按下回车键时执行操作

iphone - 获取图像大小而不加载到内存

iOS FCM 通知从 Google 控制台工作,但不是从服务器工作

iphone - 将 MPMediaItems 与 AVAudioPlayer 一起使用

iphone - 我如何在 cocos2D 应用程序中拍照 (iOS 6)

objective-c - NSNumberFormatter 只四舍五入到小数点后三位

ios - dequeueReusableCellWithIdentifier : returns nil even after creating cell instance

iphone - 如何将 vCard 中的联系人信息保存到 iPhone 的联系人应用程序中