Setup:
My app uses 2 persistent stores managed by a single persistent store coordinator that is used by several managed object contexts. Both persistent stores store the same entities.
It is required that any inserts, updates and deletes of managed objects are only done in one of both persistent stores, and the app can select the persistent store.
Problem:
In order to store a managed object only in one persistent store, I want to use func assign(_ object: Any, to store: NSPersistentStore) of a NSManagedObjectContext. The docs say
Specifies the store in which a newly inserted object will be saved.
Question:
What means „newly inserted“?
- Can I assign a persistent store as long as the object has never been saved by its context?
- Could I use, e.g., a
willSaveObjectsNotificationto loop though allregisteredObjectsof the context and assign the required persistent store?
When the app switches the persistent store, I would then reset the contexts so that all managed objects would be fetched newly, and the required persistent store could be set again in the willSaveObjectsNotification notification.
Is this the right way to go?
Based on Tom Harrington’s answer, I did the following tests.
The result is:
As long as a managed object has never been saved to a persistent store, one can use
assign(_:to:)to define one of several persistent stores into which the object will be saved later.My code: