Philip Guin
Philip Guin

Reputation: 1460

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:NSKeyValueChangeOldKey];

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?

Upvotes: 6

Views: 3465

Answers (2)

dphil
dphil

Reputation: 88

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.

Upvotes: 5

Caleb
Caleb

Reputation: 124997

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

Upvotes: 2

Related Questions