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
NSFetchedResultsController
that there are changes, but so far it doesn't pick up any changes. Is there something I should do to notify the main thread'sNSFetchedResultsController
that there were externalsave
's so that thetableView
updates accordingly?So, on the main thread, I subscribe to
NSManagedObjectContextWillSaveNotification
and correctly see when all contexts (including those existing entirely on a separate thread) perform asave
operation. The apple docs say that thenotification.userInfo
should have a dictionary of 3 arrays, one array for each of the "updated, deleted, and inserted" model objects on the background thread. However, theuserInfo
is alwaysnil
for 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.