Kevin Flachsmann
Kevin Flachsmann

Reputation: 576

NSManagedObjectContextDidSaveNotification useless?

I am using Core Data for a while now with a background contex, and was wondering why everyone advise to use the NSManagedObjectContextDidSaveNotification for merging from the background to the main context. I created a Test-Project with one NSPersistentStoreCoordinator, a main context and a background context. Here is the code fragment for initalisation:

- (NSManagedObjectContext *)managedObjectContext {

if (_managedObjectContext != nil) {
    return _managedObjectContext;
}

NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
}

return _managedObjectContext;
}



- (NSManagedObjectContext *)backgroundContext {
if (_backgroundContext != nil) {
    return _backgroundContext;
}
_backgroundContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
_backgroundContext.persistentStoreCoordinator = self.persistentStoreCoordinator;

return _backgroundContext;
}

until now, i would have listened to the save notification like this:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(mergeChanges:)
                                             name:NSManagedObjectContextDidSaveNotification
                                           object:self.backgroundContext];

But i realised, it doesn't matter if I merge from that notification. I can edit and save either context, and the other one get's merged after some seconds itself.

So. my question, why would i even need the NSManagedObjectContextDidSaveNotification?

Upvotes: 1

Views: 1736

Answers (1)

Jason Fieldman
Jason Fieldman

Reputation: 116

Your contexts are not related. They are both root contexts attached to the same persistent store coordinator.

A change to the persistent store is automatically pushed to the root contexts associated with it (which is why you don't need to handle the NSManagedObjectContextDidSaveNotification notification.)

NSManagedObjectContextDidSaveNotification is useful when dealing with more complex context ancestry, since a mid-level context does not automatically notify all of its children when changed.

As an example, check out the architecture diagram for Cadmium (https://github.com/jmfieldman/Cadmium). When a background child context saves up to the writer context, the main context must handle a NSManagedObjectContextDidSaveNotification on the main thread to incorporate the updates.

Upvotes: 3

Related Questions