Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using mergeChangesFromContextDidSaveNotification:saveNotification I am not getting changes show up in main thread

I am using a background thread to do a long running task including pulling data from service and insert records into the database via CoreData. As suggested by many answers here I am observing the NSManagedObjectContextDidSaveNotification notification. I am using these 2 methods. In mergeChanges method I see my insertions in the notification object but after both methods complete my main MOC shows only changes prior to the background thread. Why is it not reflecting new changes from the background thread. What am i missing?

- (void) registerContextDidSaveNotificationForManagedObjectContext:       (NSManagedObjectContext*) moc {
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    [nc addObserver:self
           selector:@selector(mergeChanges:)
               name:NSManagedObjectContextDidSaveNotification
             object:moc];
}

- (void)mergeChanges:(NSNotification *)notification {
    //AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *mainContext = self.managedObjectContext;

    // Merge changes into the main context on the main thread
    [mainContext performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:)
                                  withObject:notification
                               waitUntilDone:YES];
}
like image 883
Hassan Hussein Avatar asked Dec 19 '13 14:12

Hassan Hussein


1 Answers

The thread you register the NSManagedObjectContextDidSaveNotification has to be the thread you invoke [mainContext mergeChangesFromContextDidSaveNotification: notification].

For example: you register thread A NSManagedObjectContextDidSaveNotification when something change in thread B. Then you receive the notification, however, these changes are associated with thread B, you can not access the change directly, so you pass the notification as an argument to mergeChangesFromContextDidSaveNotification: (which you send to the context on thread A) to merge these changes.

So please check whether they are on the same thread?

like image 88
johnMa Avatar answered Sep 18 '22 05:09

johnMa