How to synchronise two NSManagedObjectContext


I'm working on an ipad application that use coredata. It download information on a database that is on the web, and record them in coredata. The application is based on a split view. My problem was to make the download and the record of the data in background.
Here is how I've done :
- I've create an NSOperation, that does the download and the record of the data.
- This NSOperation use a different NSManagedObjectContext than the context of the appDelegate, return by this function, that is in the appDelegate :

(NSManagedObjectContext*)newContextToMainStore {
     NSPersistentStoreCoordinator *coord = nil;
     coord = [self persistentStoreCoordinator];
     NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] init]; 
     [moc setPersistentStoreCoordinator:coord]; 
     return [moc autorelease];
}

- I've had an observer in the NSOperation, that will call this function in the appDelegate when I save the context, to modify the context of the delegate too :

- (void)mergeChangesFromContextSaveNotification:(NSNotification*)notification {
     [[self managedObjectContext]mergeChangesFromContextDidSaveNotification:notification];
}

But I've a problem, the synchronisation doesn't work, because the data on the rootViewController (that is a UITableViewController), that have a NSManagedObjectContext initialised with the context of the appDelegate and use as datasource a NSFetchedResultsController, don't actualise automatically the informations, as it normaly must do.
So I ask you :
What did I do wrong ? Is it the good way to use two different context and synchonise them ?


What you have here looks correct. You do want to make sure you implement the NSFetchedResultControllerDelegate methods in the rootViewController so the changes will appear in the UI.

链接地址: http://www.djcxy.com/p/91650.html

上一篇: 如何通过Interface Builder的XIB传递NSManagedObjectContext

下一篇: 如何同步两个NSManagedObjectContext