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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With