开发者

KVO and Core Data, Getting only the Changed Values through Observation

So I'm fairly new to Core Data and KVO, but I have an NSManagedObject subclass that is successfully observing its own to-many relationship. The problem is, on observed changes, I want to iterate through only the set of objects that were added or removed. Is there some way to access these items directly? Or must I do something relatively inefficient like:

NSSet* newSet = (NSSet*)[change objectForKey:NSKeyValueChangeNewKey];
NSSet* oldSet = (NSSet*)[change objectForKey:NSKeyValueChangeOl开发者_StackOverflowdKey];

NSMutableSet* changedValues = [[NSMutableSet alloc] initWithSet:newSet];
[changedValues minusSet:oldSet];

I feel like you should be able to avoid this because in these messages...

[self willChangeValueForKey:forSetMutation:usingObjects:];
[self  didChangeValueForKey:forSetMutation:usingObjects:];

you're handing it the added/removed objects! Perhaps knowledge of what happens to these objects would be helpful?


Have you actually examined the contents of the "old" and "new" values provided by the KV observation? When I observe a change in a mutable set triggered by didChangeValueForKey:forSetMutation:usingObjects:, the change dictionary value for NSKeyValueChangeNewKey holds only any added objects, while the value for NSKeyValueChangeOldKey holds only any removed objects, so you shouldn't have to manually figure out what has changed. However, an observation triggered by didChangeValue:forKey: will give you the entire old collection for NSKeyValueChangeOldKey and the entire new collection for NSKeyValueChangeNewKey, even if they have identical contents.


When you register to observe an object, include the NSKeyValueObservingOptionNew option (and NSKeyValueObservingOptionOld too, if you want).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜