Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 419
Philip Guin Avatar asked Jul 04 '11 22:07

Philip Guin


People also ask

What is KVO Key-Value observation)?

KVO, which stands for Key-Value Observing, is one of the techniques for observing the program state changes available in Objective-C and Swift. The concept is simple: when we have an object with some instance variables, KVO allows other objects to establish surveillance on changes for any of those instance variables.

What is Key-Value coding and Key-Value observing?

KVO and KVC or Key-Value Observing and Key-Value Coding are mechanisms originally built and provided by Objective-C that allows us to locate and interact with the underlying properties of a class that inherits NSObject at runtime.

What is KVO in Objective-C?

KVO allows you to register as an observer of a given object and receive notification when specific properties on that object are changed. It's an incredibly powerful capability, and it is built into Objective-C at its very core.


1 Answers

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.

like image 190
dphil Avatar answered Oct 21 '22 00:10

dphil