I would say that listening to the NSManagedObjectContextObjectsDidChangeNotification notification is not the best solution.
How do I do it and it works. Here is the basic context creation:
_mainContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType]; _mainContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy; _mainContext.persistentStoreCoordinator = _persistentStoreCoordinator;
Here is the creation of the background context:
_backgroundContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType]; _backgroundContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy; _backgroundContext.parentContext = self.mainContext;
Now the background context is intended only for writing (or reading) objects (it can be in the background thread). The main context is read-only from the main queue. Save in the background context should look like this:
__block BOOL saved = [_backgroundContext save:error]; if (saved && _backgroundContext.parentContext) { [_backgroundContext.parentContext performBlockAndWait:^{ saved = [self.parentContext save:error]; }]; }
This save method ensures that all changes are propagated in the main context. If you work a lot in many background threads, performBlockAndWait: method, which provides mutual exclusion in context.
If you want to be notified of changes to objects, you do not need to listen to the notification, you can simply set up NSFetchedResultsController and register as your delegate.
source share