我对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]];
答案 0 :(得分:3)
只是为了确保问题得到解答。信用转到@DoubleDunk
[self willChangeValueForKey:@"someDictionary" withSetMutation:NSKeyValueUnionSetMutation usingObjects:[NSSet setWithObject:someObject]];
[Images setObject:someObject forKey:someIndex];
[self didChangeValueForKey:@"someDictionary" withSetMutation:NSKeyValueUnionSetMutation usingObjects:[NSSet setWithObject:someObject]];