ios – NSMutableDictionary添加和删除KVO

前端之家收集整理的这篇文章主要介绍了ios – NSMutableDictionary添加和删除KVO前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个关于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]];

解决方法

只是为了确保回答问题.信用转到@DoubleDunk
[self willChangeValueForKey:@"someDictionary" withSetMutation:NSKeyValueUnionSetMutation usingObjects:[NSSet setWithObject:someObject]];

    [Images setObject:someObject forKey:someIndex];

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

猜你在找的iOS相关文章