简体   繁体   English

NSMutableDictionary 增删KVO

[英]NSMutableDictionary addition and removal KVO

I have a quick question regarding KVO.我有一个关于 KVO 的快速问题。 I understand that for a NSArray if observing additions is desired you can do the following.我知道对于 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"];

Upon registering for observation you will get a change dictionary with the indexes that changed.注册观察后,您将获得一个包含已更改索引的更改字典。

However, I do not understand how I can observe new object additions to a NSMutableDictionary.但是,我不明白如何观察 NSMutableDictionary 中新增的 object。 Is there a way to observe object add/removal?有没有办法观察 object 添加/删除?

Thanks,谢谢,

[EDIT] I found a solution which meets my current needs. [编辑] 我找到了一个满足我当前需求的解决方案。 I hope the following helps any future developers.我希望以下内容对任何未来的开发人员有所帮助。

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

[Images setObject:someObject forKey:someIndex];

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

Just to make sure that question is answered.只是为了确保这个问题得到回答。 credit goes to @DoubleDunk归功于@DoubleDunk

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

    [Images setObject:someObject forKey:someIndex];

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM