KVO nsmutablearray删除对象通知

时间:2011-10-31 19:37:56

标签: 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"];
}

我“观察”从另一个类对这个数组所做的更改 我的rootviewcontroller

    [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应该有我的对象,但它只有一个键“kind”,总是等于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"]);

1 个答案:

答案 0 :(得分:3)

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