How to tear down your Core Data Stack

You may have heard this expression before: “You need to tear down your Core Data stack before you do xyz”. It’s frequently mentioned in the Apple documentation – sadly without telling us what on earth this means or how to do it.

I had assumed that it means rebuilding every aspect of Core Data, which without a complete app re-launch looks like a daunting task. But it’s relatively easy if you know how to do it. In this article I’ll show you how.

The secret is in the NSPersistentStoreCoordinator: all we really have to do is remove the store files from it and then add them again. Here’s a method that does just that and more (add it to your AppDelegate.m file to use it):

Let’s go through this line by line: first we’ll lock and reset our managed object context for safe measure. This will make sure no other thread is working with it while we’re meddling.

Next we’ll iterate through all possible store files in our coordinator. The Core Data template provide only one, but just in case you have more, we’ll remove them all. In this loop we’re also deleting all files from the hard drive.

Then we set the variables of both coordinator and object context to nil – an ingenious tip from Luke McNeice (Thanks, Luke!) We do this because in the next step we can just call the custom initialiser for self managedObjectContext again which will rebuild the stack.

Finally we unlock the context so other threads can access it concurrently.

Demo Project

Here’s a fully working Demo Project on GitHub which employs this technique. It’s based on the Master/Detail Template and adds an extra button to tear down the stack in a running iOS App:

Further Reading

Watch the full course in one convenient playlist:
Catch this episode on my iOS Dev Diary Podcast:

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.

2 thoughts on “How to tear down your Core Data Stack

Leave a Reply

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