How to swap out a store file in Core Data

You can switch out the NSPersistentStore file in your running Core Data app by first adding your new store file, then removing the previous one. Once done you must execute your fetch request again so that the new data is available.

Hot-swapping stores assumes both NSPersistentStore files are based on the same model. It’s like replacing a USB stick.

First let’s pass a reference of the Persistent Store Coordinator into the class you’d like to make the switch in. Based on the Xcode Utility Project, that’s MainViewController. The Core Data stack is already setup in the App Delegate, so we’ll pass a reference here:

Test this by fetching your data before and after the swap. You don’t have to remove the second store, you can leave it in place if you’d like to fetch data from both stores. I’m not sure though what will happen if you add data – it may end up in both stores.

To check if your store file has changed, you can subscribe to this notification: