I have an NSFetchedResultsController on the main thread. Also from the main thread, I asynchronously send out a network request for JSON. When that JSON string returns, I start an NSOperation that inits a new (background) NSManagedObjectContext, parses the JSON string, creates/updates NSManagedObject‘s, and saves them in the context. The background context has the same persistentStore as the main context. With this, I have 2 questions:
-
I thought that any saves to the persistent store from any context (on any thread) would notify the main
NSFetchedResultsControllerthat there are changes, but so far it doesn’t pick up any changes. Is there something I should do to notify the main thread’sNSFetchedResultsControllerthat there were externalsave‘s so that thetableViewupdates accordingly? -
So, on the main thread, I subscribe to
NSManagedObjectContextWillSaveNotificationand correctly see when all contexts (including those existing entirely on a separate thread) perform asaveoperation. The apple docs say that thenotification.userInfoshould have a dictionary of 3 arrays, one array for each of the “updated, deleted, and inserted” model objects on the background thread. However, theuserInfois alwaysnilfor me. Any ideas what I’m doing wrong?
Subscribing to the NSManagedObjectContextWillSaveNotification in AppDelegate:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(managedObjectContextDidSave:)
name:NSManagedObjectContextWillSaveNotification
object:nil];
And the method for when contexts are saved in AppDelegate:
- (void)managedObjectContextDidSave:(NSNotification *)notification {
DLog(@"notification: %@", notification); //not nil
DLog(@"notification user info: %@", notification.userInfo); // always nil... why??
NSManagedObjectContext *theContext = notification.object;
if(theContext != context) {
DLog(@"---- SAVED ON ANOTHER CONTEXT");
// should I notify NSFetchedResultsController that there were context saves on background threads?
// how can I merge contexts if userInfo is nil?
}
}
I’d also like to know the best practices in dealing with multiple threads (with separate NSManagedObjectContexts) and Core Data.
You observe the wrong notification: the name of the notification you need to observe is
NSManagedObjectContextDidSaveNotification(notNSManagedObjectContextWillSaveNotification).