In the other answer I found 1,2 and 3 too inefficient. Particularly 2 and the example in the "Parent Watching it's Child" blog post. My issue with that is every single parent had to respond to the context notification and essentially every object being saved if it is the child (never mind the fact ContextDidSave is more appropriate in that case!). Instead, I would propose an option 4:
- Have the child override didSave and broadcast a NSManagedObjectContextDidSaveNotification containing the parent.
My solution is more efficient and feels more object-oriented to me since the object that is changing is responding to its own change. To implement this, within the child object use:
-(void)didSave{
[super didSave];
// notify that the parent has changed.
[[NSNotificationCenter defaultCenter] postNotificationName:NSManagedObjectContextObjectsDidChangeNotification
object:self.managedObjectContext
userInfo:@{NSUpdatedObjectsKey : [NSSet setWithObject:self.parent]}];;
}
To update the parent timestamp, the following neat solution (second last post) I've been using might help, e.g. in the parent use:
- (void) awakeFromInsert
{
[super awakeFromInsert];
// set the default dates
NSDate* date = [NSDate date];
self.timestamp = date;
//allow any future modifications to change the timestamp
_finishedStartup = YES;
}
- (void) awakeFromFetch
{
[super awakeFromFetch];
// we should already have creation and modified dates.
_finishedStartup = YES;
}
- (void) didChangeValueForKey: (NSString *) thisKey
{
[super didChangeValueForKey: thisKey];
if(![thisKey isEqualToString:@"timestamp"] && // prevent infinite loop
![self isFault] &&
![[[self managedObjectContext] undoManager] isUndoing] &&
_finishedStartup) // ensures we arent being called by the object being loaded from fetched data.
{
self.timestamp = [NSDate date];
}
}