How to switch between Core Data Persistent Stores?

What is the best way to switch between Core Data Persistent Stores?

My use case is that I have a multi-user app that stores thousands of data items unique to each user. To me, having Persistent Stores for each user seems like the best design to keep their data separate and private. (If anyone believes that storing the data for all users in one Persistent Store is a better design, I'd appreciate hearing from them.)

Customers might switch users 5 to 10 times a day. Switching users must be fast, say a second or two at most.

Answered by DTS Engineer in 843673022

You can use replacePersistentStore(at:destinationOptions:withPersistentStoreFrom:sourceOptions:type:) to replace one persistent store with another in your Core Data stack. Alternatively, you can release your current persistent container (NSPersistentContainer) (and all Core Data objects associated with it), and create a new container with a new store URL.

Regarding putting data into one single store vs separating it into different stores, it really depends on your concrete use case. One thing I'd consider is that every Core Data store has at least two files (the main database and the wal file), and if you have a lot of users, managing many files in the file system, if needed, may become an issue. In general, using a single store simplified the data access – Use your case as an example, you will then not need to switch the stores.

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

You can use replacePersistentStore(at:destinationOptions:withPersistentStoreFrom:sourceOptions:type:) to replace one persistent store with another in your Core Data stack. Alternatively, you can release your current persistent container (NSPersistentContainer) (and all Core Data objects associated with it), and create a new container with a new store URL.

Regarding putting data into one single store vs separating it into different stores, it really depends on your concrete use case. One thing I'd consider is that every Core Data store has at least two files (the main database and the wal file), and if you have a lot of users, managing many files in the file system, if needed, may become an issue. In general, using a single store simplified the data access – Use your case as an example, you will then not need to switch the stores.

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

How to switch between Core Data Persistent Stores?
 
 
Q