I have two instances of NSManagedObjectContext
: one is used in main thread and the other is used in a background thread (via an NSOperation
.) For thread safety, these two contexts only share an NSPersistentStoreCoordinator
.
The problem I'm having is with pending changes in the first context (on the main thread) not being available to the second context until a -save
is performed. This is understandable since the shared persistent store won't have copies of the NSManagedObjects
being tracked by -insertedObjects
, -updatedObjects
, and -deletedObjects
are persisted.
Unfortunately, this presents a problem with the user experience: any unsaved changes won't appear in the (time consuming) reports that are generated in the background thread.
The only solution I can think of is nasty: take the inserted, updated and deleted objects from the first context and graft them onto the object graph of the second context. There are some pretty complex relations in the dataset, so I'm hesitant to go in this direction. I'm hoping someone here as a better solution.
If this is under 10.7 there are some solutions: one is you can have nested ManagedObjectContexts, so you can “save” in the one being modified and it won’t save all the way to the disk, but it will make the changes available to other children of the master context.
Before 10.7 you will probably have to copy the changes over yourself. This isn’t super-hard since you can just have a single object listen for NSManagedObjectContextObjectsDidChangeNotification
and then just re-apply the changes exactly from the main context. (Should be about 20 lines of code.) You never have to save this second context I assume?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With