The problem is here:
[[NSNotificationCenter defaultCenter] addObserver:self.managedObjectContext
selector:@selector(mergeChangesFromContextDidSaveNotification:)
name:NSManagedObjectContextDidSaveNotification
object:localContext];
You're linking your main-thread context directly to your background-queue context. When localContext
, running on your background thread, posts a notification, the notification is delivered to its observers (self.managedObjectContext
) on the same queue - the background queue.
You need transfer the notification to the main thread before delivering it to self.managedObjectContext
. Give yourself a new method to receive the notification on the background queue and forward it to the main thread:
- (void)backgroundContextDidSave:(NSNotification *)note {
dispatch_async(dispatch_get_main_queue(), ^{
[self.managedObjectContext mergeChangesFromContextDidSaveNotification:note];
});
}
Then use that method selector when you register for notifications:
[[NSNotificationCenter defaultCenter] addObserver:self.managedObjectContext
selector:@selector(backgroundContextDidSave:)
name:NSManagedObjectContextDidSaveNotification
object:localContext];