I'm experiencing a weird behavior when using a secondary thread to refresh NSFetchedResultsController contents and I'd like to know it this is a common issue or I might be doing something wrong.
I've got a centralized NSManagedObjectContext residing in my main delegate object which is used and shared by all view controllers. After loading a table by executing a fetch and calling its delegate method, a secondary thread is launched in background to update its results. However, and only in strange occasions, when inserting new entries they get duplicated in the table view. If I exit and reenter, duplicated rows disappear, what makes think they've only have existed in the managed object context.
These are the followed steps:
- A background NSOperation thread creates a confined context linked to the same persistent store of the main application delegate.
- The new thread starts listening NSManagedObjectContextDidSaveNotification notifications.
- New rows are deleted, updated or inserted into the secondary context making always a save call when reaching some batch size.
When saving in the background, the notification method calls the centralized context mergeChangesFromContextDidSaveNotification selector on the main thread as follow.
-(void)mergeChanges:(NSNotification *)notification { NSManagedObjectContext *mainContext = [[appDelegate sharedDelegate] managedObjectContext]; [mainContext performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:) withObject:notification waitUntilDone:NO]; }
After finishing the operation the listener is removed and the secondary context released.
Does anybody have idea what is the reason is causing my table view rows to get duplicated, and how it can be solved?
Thanks in advance for your help.