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

2

6

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?

Laresa answered 4/7, 2011 at 22:3 Comment(0)
P
5

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.

Pestilence answered 7/11, 2011 at 19:53 Comment(1)
Ah, thank you! I suppose I was just subtracting items that were already missing from the set, then :P I believe I read the latter case somewhere in the Apple docs, but I didn't realize it applied differently to didChangeValueForKey:withSetMutation:usingObjects: Not exactly intuitive, is it?Laresa
C
2

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

Clubhouse answered 5/7, 2011 at 18:14 Comment(1)
Thanks, I had already done this, but good to clarify. I'd still rather avoid this solution if at all possible.Laresa

© 2022 - 2024 — McMap. All rights reserved.