How to tear down your Core Data Stack

Core-Data-IconYou 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):

- (void)rebuildCoreData {
    [self.managedObjectContext lock];
    [self.managedObjectContext reset];
    NSArray *stores = self.persistentStoreCoordinator.persistentStores;
    for (NSPersistentStore *currentStore in stores) {
        // remove store files
        [self.persistentStoreCoordinator removePersistentStore:currentStore error:nil];

        // delete those store files
        [[NSFileManager defaultManager]removeItemAtURL:currentStore.URL error:nil];
    _managedObjectContext = nil;
    _persistentStoreCoordinator = nil;
    [self managedObjectContext];
    [self.managedObjectContext unlock];

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.

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:


I’m explaining how to do all this in a screencast too:

Further Reading

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

Leave a Reply