KVO addObserver to CoreData object's one-to-many relationship

Peterdeka picture Peterdeka · Mar 27, 2013 · Viewed 7.6k times · Source

Hi everyone years reading StackOverflow, now I decided to join. I am struggling to get this resolved:

I have a "Depot" entity that has two to-many relationships "Persons" and "Trucks". I want to observe when, given a "Depot" object, there are changes (insert,remove) in one of the relationships (and understand in which one).

Currently i am doing this:

[mydepot addObserver:self forKeyPath:@"Trucks" options:NSKeyValueObservingOptionNew context:nil];

and

[mydepot addObserver:self forKeyPath:@"Persons" options:NSKeyValueObservingOptionNew context:nil];

but everytime something changes in one of the two related collections, observeValueForKeyPath gets called twice (one time for each keypath).

Am i doing it wrong? Looking at "change" dict, (observing with also OptionOld) shows no unexpected changes (when i change persons, trucks is not changed) but the notification is still raised.

Thanks, Pietro

edit: it seems that both times the "change" dict contains the entire relationship in the "new" field. (obviously one time Persons and one time Trucks)

edit2:as it happens even bserving simple properties, could it be related to the managedctx save operation? as if when you save, the entire object is considered changed..

Answer

Mundi picture Mundi · Mar 27, 2013

In the Key Value Observing Programming Guide it says that

If you're using Core Data, you can register the parent with the application's notification center as an observer of its managed object context. The parent should respond to relevant change notifications posted by the children in a manner similar to that for key-value observing.

That could effectively mean that the recommended practice is not to use addObserver:forKeyPath:options:context:, but register for the NSManagedObjectContextDidSaveNotification instead.