【问题标题】:NSMutableDictionary addition and removal KVONSMutableDictionary 增删KVO
【发布时间】:2011-07-05 16:42:50
【问题描述】:

我有一个关于 KVO 的快速问题。我知道对于 NSArray,如果需要观察添加,您可以执行以下操作。

 NSIndexSet* set = [NSIndexSet indexSetWithIndex:[someIndex integerValue]];
            [self willChange:NSKeyValueChangeInsertion valuesAtIndexes:set forKey:@"theArrayName"];
                // add the objects at the specified indexes here
            [self didChange:NSKeyValueChangeInsertion valuesAtIndexes:set forKey:@"theArrayName"];

注册观察后,您将获得一个包含已更改索引的更改字典。

但是,我不明白如何观察 NSMutableDictionary 中添加的新对象。有没有办法观察对象添加/删除?

谢谢,

[编辑] 我找到了满足我当前需求的解决方案。我希望以下内容对任何未来的开发人员有所帮助。

[self willChangeValueForKey:@"someDictionary" withSetMutation:NSKeyValueUnionSetMutation usingObjects:[NSSet setWithObject:someObject]];

[Images setObject:someObject forKey:someIndex];

[self didChangeValueForKey:@"someDictionary" withSetMutation:NSKeyValueUnionSetMutation usingObjects:[NSSet setWithObject:someObject]];

【问题讨论】:

  • +1 。好问题/答案。您应该将嵌入问题中的答案作为答案发布。您目前在“未答复”列表中。实际上鼓励在 SO 上发布您自己问题的答案。还鼓励在发布答案后立即提出您已经知道答案的问题(假设该问题是其他人也可能遇到的好问题)。

标签: ios cocoa-touch collections nsmutabledictionary key-value-observing


【解决方案1】:

只是为了确保该问题得到解答。归功于@DoubleDunk

[self willChangeValueForKey:@"someDictionary" withSetMutation:NSKeyValueUnionSetMutation usingObjects:[NSSet setWithObject:someObject]];

    [Images setObject:someObject forKey:someIndex];

    [self didChangeValueForKey:@"someDictionary" withSetMutation:NSKeyValueUnionSetMutation usingObjects:[NSSet setWithObject:someObject]];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多