Search code examples
ioscore-datacore-data-migration

Update iOS Core Data Version to Avoid a Crash


I updated my iOS app and this included making a number of changes to the Core Data model. Then after I uploaded the new version to the App Store and people started trying to use it the app crashed!

I now understand that this is because the users had the old Core Data on model on their devices and it isn't compatible with the new one. I've read that I should have updated the model version so now that's what I'm doing.

I'm slightly nervous about it though as I've read that I should have updated the model version BEFORE making the changes. Obviously I can't go back in time - the changes are made and I didn't update the eversion BEFORE I made them. So will it be ok to just change the model version now and expect it to work ok on my users devices without crashing or is there something else I can / must do?

The actual data isn't very important and will soon be replaced so I don't care if they can keep the data or not. I just need them to be able to update the app without it crashing when they next try to use it.


Solution

  • If you are using any version control system, you can retrieve the old model and do it the right way, follow this documentation to do so.

    In order to stop the users app from crashing, you can erase the old sqlite file and generate a new one using the updated model.

    You can do something similar to this code. Notice that this will erase the sqlite file every time your app is not able to open it

    __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
    
    if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error]) 
    {
        if(error)
        {
            //Erase old sqlite
            [[NSFileManager defaultManager] removeItemAtURL:storeURL error:&error];
    
            //Make new persistent store for future saves 
            if (![self.persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {
                // do something with the error
            }
        }
    }