Search code examples
ioscore-dataentity-relationship

Notify parent Entity when child Relationship Entity changes in Core Data


Is it possible to receive a callback or notification in the parent Entity when any one it's relationship objects changes? This works great when an attribute of the Entity changes. The following method...

- (void)didChangeValueForKey:(NSString *)key

is invoked on my Entity subclass. However this method is not invoked when an attribute in one of the relationships changes.

What I'm trying to do is update the timeStamp attribute on my parent Entity when any one of its attributes or relationship objects changes.


Solution

  • The parent entity can set itself as an observer of the relationship and it will get notified when that relationship changes. However that will only be fired when the actual relationship (adding or removing a child) occurs.

    To watch for a specific child entity is far more tricky. There are a couple of ways to go about it:

    1. Have the child ping the parent when its properties change.
    2. Have the parent listen for NSManagedObjectContextDidSaveNotification and look to see if any of its children are in that save
    3. Have the parent observe the values on the children.

    There may be other solutions but of the three I recommend #2. It is pretty easy to set up and the performance impact is pretty minimal.