ioscore-datanspersistentstore

Coredata: How to use alternatively 2 persistent stores with one persistent store coordinator?


The setup:
My app uses uses either own data (own state) or data shared by another user (shared state), and it is possible to switch between both states.
The app uses Coredata with CloudKit mirroring: Own data are stored in the private database, and shared data in the shared database. Both databases are synchronized automatically to two persistent stores, private and shared, coordinated by a single persistent store coordinator.
If in own state, data should be fetched from the private store and stored only there.
Alternatively, in shared state, data should be fetched from the shared store and stored only there.
It is now possible to fetch data only from specific stores by setting the affectedStores property of a fetch request appropriately.
But apparently it is not possible to set affected stores for saving changes of a managed object context.

The question:
How can I achieve that managed object changes are only saved to one of the persistent stores?

My ideas:


Solution

  • I just found by chance a solution to my problem in this post under „Update“:
    It is possible to tell a managed object context to assign all newly inserted objects a persistent store to which they are saved, see the Apple docs.
    Thus, I can reset the relevant context, and use assign(_:to:) to direct saves to the specific persistent store.