I have a UITableView that fetches data from CoreData using FetchedResultsController and it registers for the data update.
On a second thread, I download the data from the server and update the same data (that’s used by the UITableView). The update is not complicated and It is just updating a BOOL field of the entity.
When I call the save on Object Context, I get this exception: NSInternalInconsistencyException and the reason is
"Failed to process pending changes before save. The context is still dirty after 100 attempts. ..."
If I do not save right after the update but only at the time when the application is about to terminate, the application runs fine and the UITableView is correctly updated and the data is persisted.
Any pointer on why that might be happening? Am I doing something wrong?
Managed object contexts are not thread safe. Do you have a separate
MOCfor each thread?If so, I believe the correct pattern is to register for
NSManagedObjectDidSaveNotificationsfrom the backgroundMOCsuch that you can do amergeChangesFromContextDidSaveNotificationon the mainMOC(from the main thread). This will keep yourMOCsin sync; it does not happen automatically.