I am using a basic template NSPersistentDocument
for a Core Data-based application. Because my program is CPU-intensive, I have been forced to multithread it. From what I know, the best way to multithread Core-Data is to create a new NSManagedObjectContext
for each thread and pass the object ID between threads. My question operates under this conception, but if it is false, please say so.
So the issue is thus: upon startup of the application, a new empty document is created. This document has a managed object context and associated NSPersistentStoreCoordinator
, but no persistent store (which I assume is created on save, but I haven't tested). I have functionality to create NSManagedObject
s, but since they are multithreaded, they require a separate managed object context. On the finalization of the creation of the managed object, I call save:
on the context to ensure that other managed object contexts see the up-to-date managed object values. Without a persistent store, however, this throws the error:This NSPersistentStoreCoordinator has no persistent stores. It cannot perform a save operation.
So to overcome this, I implemented a separate NSPersistentStoreCoordinator
and an in-memory NSPersistentStore
. This PSC gets passed around (in the main thread) and is the PSC for the threaded managed object contents which handle additional managed object creation. However, in addition to this seeming like bad practice (I envision a single NSPersistentStoreCoordinator
per document) it adds additional overhead as each time a managed object must be 'moved' to the document to enable it to be saved, it must be copied value by value. The issue is that I do not want to persist every managed object that is created to the document.
If I create an in-memory store for the persistent store coordinator after the new document is created, but before the file has been determined as the on-disk store, the document reverts back to that store to 'persist' the managed objects. However, because the file has not been saved, I cannot find the persistent store to use in assignObject:toPersistentStore:
in NSManagedObjectContext
when officially adding the managed object to the document.
With the document only maintaining this 'ghost' persistent store for the document, everything works fine.
It feels like a catch 22.
Basically I'm looking for a better way to keep a managed object on the persistent document while the document waits for the user to save - without value-by-value copying which would decrease the system load of the application and messy code which I have to maintain every time the object graph changes.
I appreciate your responses. Let me know if more detail is needed.