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:

Now that our MainViewController can use the coordinator, here’s how we can switch to a new file. I’m calling the current one store1 and the new one store2:

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:

  • NSPersistentStoreCoordinatorStoresDidChangeNotification

Here’s an iOS Demo Project that I’ve put together:

About Jay Versluis

Jay is a medical miracle known as Super Survivor. He runs two YouTube channels, five websites and several podcast feeds. To see what else he's up to, and to support him on his mission to make the world a better place, check out his Patreon Campaign.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.