KVO and master data, receiving only changed values ​​through observation

So, I'm pretty new to Core Data and KVO, but I have a subclass of NSManagedObject that successfully respects its own relationships with many. The problem is that with the observed changes, I want to iterate through only a set of objects that have been added or deleted. Is there a way to access these elements directly? Or should I do something relatively inefficient, like this:

NSSet* newSet = (NSSet*)[change objectForKey:NSKeyValueChangeNewKey]; NSSet* oldSet = (NSSet*)[change objectForKey:NSKeyValueChangeOldKey]; NSMutableSet* changedValues = [[NSMutableSet alloc] initWithSet:newSet]; [changedValues minusSet:oldSet]; 

I feel that you should be able to avoid this, because in these posts ...

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

you pass it the added / deleted objects! Perhaps it is useful to know what happens to these objects?

+6
source share
2 answers

Have you really studied the contents of the “old” and “new” values ​​provided by the KV observation? When I observe a change in the mutable set caused by didChangeValueForKey:forSetMutation:usingObjects: value of the change dictionary for NSKeyValueChangeNewKey contains only any added objects, while the NSKeyValueChangeOldKey value contains only any deleted objects, so you do not need to manually determine what has changed. However, the observation caused by didChangeValue:forKey: will provide you with the entire old collection for NSKeyValueChangeOldKey and the whole new collection for NSKeyValueChangeNewKey, even if they have the same content.

+5
source

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

+2
source

Source: https://habr.com/ru/post/891989/


All Articles