CoreData: Merge two contexts before saving the document
I'm writing Coredata document-based application (i.e. CoreData+NSPersistentDocument): as I create a new document, a new coredata stack is initialized, with a model and a single managed context.
Before the user saves开发者_StackOverflow the document, what I need to do is: - create a new context - create many new managed objects in it - merge the two contexts.
I issue save: on the new context, but it raises the exception "This NSPersistentStoreCoordinator has no persistent stores. It cannot perform a save operation.".
How I can do? Should I need to save the document before this operation?
By the way, if I save the document, create a new context, import data and save the new context and finally save the document context, I get the following message: "This document’s file has been changed by another application since you opened or saved it."; any ideas?
Best regards!
The underlying issue is that NSPersistentDocument
does an atomic save whereby the documents NSManagedObjectConext
is saved to a temporary file and then that file is swapped atomically with the file at the document's URL (if it exists). The timing of this swap is not public, making it nearly impossible for an NSPersistentDocument
subclass to know the URL of the (temporary) persistent store during the save operation. I believe your only option is to override -[NSPersistentDocument writeToURL:ofType:forSaveOperation:originalContentsURL:error:]
so that you can save your new context once the persistent store is created.
For reference, I've filed this bug with Apple under rdar://6510616 (please feel free to duplicate it to vote for a fix).
精彩评论