I\'m currently having an issue where creating a new object on a background child thread (whose parent is the main UI thread context) and saving causes my NSFetchedResultsC
I had the exact same issue, of course after a particularly difficult and dispiriting day of debugging everything to find out the issue was temporary IDs. :)
I have the exact same structure as you, and I also have subclasses of NSManagedObjectContext to codify the behavior I expect of saves in the background and main contexts – namely, a save in the background context should save the main context (and the main context should sync any objects that changed with the external service, which is irrelevant but worth mentioning as an explanation for why I have two subclasses), and a save in the main context should save the master context.
In my RFSImportContext subclass (equivalent to your backgroundMOC), I implement - save:
to call [super save:]
, then call [self.parentContext performBlock:]
(self.parentContext here is equivalent to your mainM)C, where the block calls obtainPermanentIDsForObjects:
with the contents of the main context's - updatedObjects
and - insertedObjects
arrays, then I save the main context.
I no longer have the leaking of temporary objects into my NSFetchedResultsController as you describe. A way to improve the situation a bit would be to use the RFSMainContext subclass (again, equivalent to your mainMOC) to implement - save:
to obtain permanent object IDs, save itself, then save the master context. This codifies the behavior that we always want the main context to have permanent IDs for objects in it when it is saved.