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];
}
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With