iOS : Core Data migration

Since the beginning, I use Core Data in my iOS applications to store data. I just use them as simple as it could without any migration or versioning options. For sure during the development phase, my apps were crashing each time I modified the Core Data Model.
So I finally decided to have a look on that…. Yes, finally ;o) In fact, it’s really simple…..

So first, you have to put the code in your app delegate :

NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"myDataBase.sqlite"]];

NSError *error = nil;
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
// handle db upgrade
NSDictionary *dbOptions = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];

if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:dbOptions error:&error]) {
//handle error
}

After that, when you want to modify your database in your project, you have to create the new file in your project.
1 – select your data model,
2 – click on Editor and choose “Add Model Version”. XCode propose you a New Version Name. You can choose this one.
3 – open the right panel of XCode and expand “Versioned Core Data Model”. Choose the new file you just created. It will be integrated in your app.

As simple as that, you can now modify your Core Data Model when ever you want when delivering new apps to Apple !

This entry was posted in iOS, tutoriels. Bookmark the permalink.