gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 06:09:19 25 4
gpt4 key购买 nike

我有一个带有 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"];
}

我“观察”了另一个类对该数组所做的更改
我的根 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com