我有一个关于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]];