NSFetchedResultsController duplicates rows

I am having strange behavior when using a secondary stream to update the contents of an NSFetchedResultsController, and I would like to know that this is a common problem, or I might do something wrong.

I have a centralized NSManagedObjectContext which is in my main delet, which is used and used by all dispatchers. After the table is loaded, by fetching and calling its delegation method, the secondary thread starts in the background to update its results. However, and only in strange cases when inserting new records, they are duplicated in the table view. If I go out and return, the repeated lines will disappear, which makes me think that they exist only in the context of the managed object.

These are the following steps:

  • The NSOperation background thread creates a restricted context associated with the same persistent storage of the main delegate application.
  • The new thread starts listening for NSManagedObjectContextDidSaveNotification notifications.
  • New lines are deleted, updated, or inserted into the secondary context, always making a save call when the batch size is reached.
  • When stored in the background, the notification method calls the central context selector mergeChangesFromContextDidSaveNotification in the main thread, as shown below.

    -(void)mergeChanges:(NSNotification *)notification { NSManagedObjectContext *mainContext = [[appDelegate sharedDelegate] managedObjectContext]; [mainContext performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:) withObject:notification waitUntilDone:NO]; } 
  • After the operation is completed, the listener is deleted and the secondary context is freed.

Does anyone have any ideas what is the reason that the rows of the table view table are duplicated and how can they be solved?

Thanks in advance for your help.

+7
source share
1 answer

In fact, you cannot have “duplicated” objects in the context of a managed object, because each object in the context must be unique. Maintaining unique objects is the main function of the context, so this just doesn't happen. So, you have one of two conditions:

  • You create two or more managed objects with the same attributes that appear together when sorted as a table.
  • Your datasource tableview logic actually returns to the table a view of the data from the same managed entity twice in some cases. This will create the illusion that in the context there is a duplicated managed entity.

I think the latter is more likely.

+1
source

All Articles