我有一个带有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/