Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSFetchedResultsController duplicated rows

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:

  1. A background NSOperation thread creates a confined context linked to the same persistent store of the main application delegate.
  2. The new thread starts listening NSManagedObjectContextDidSaveNotification notifications.
  3. New rows are deleted, updated or inserted into the secondary context making always a save call when reaching some batch size.
  4. 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];
    }
    
  5. 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.

like image 491
Miguel Ángel Ortuño Avatar asked Jun 08 '11 11:06

Miguel Ángel Ortuño


1 Answers

You can't actually have "duplicated" objects in a managed object context because every object in a context must be unique. Maintaining unique objects is the core function of a context so it just doesn't happen. So, you have one of two condtions:

  1. You are creating two or more managed objects with the same attributes such that they show up together when sorted into a tableview.
  2. Your tableview datasource logic is actually returning to the tableview the data from the same managed object twice in some circumstances. This would create the illusion that there is a duplicate managed object in the context.

I think the latter more likely.

like image 176
TechZen Avatar answered Dec 05 '22 00:12

TechZen