Automatically update store schema with Core Data

Automatically update store schema with Core Data

August 17, 2011 09:25 3 comments
10 Kudos

Today I was playing with Core Data technology and I was trying to check whether it is possible to update the store schema according to the changes I made to the entities, relationships and whatever else.

I found out that the important steps are:

  • Use the versioning: before modifying your current schema you should select “Editor -> Add Model Version..”
  • Edit as much as you like
  • Select the new version as the active one
  • Go to your app delegate file and modify the - (NSPersistentStoreCoordinator *) persistentStoreCoordinator method as follows:
    NSURL *url = [applicationFilesDirectory URLByAppendingPathComponent:@"YourApp.storedata"];
        __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom];
    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:  
    						 [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,  
    						 [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
    if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:options error:&error]) {
    		// The rest of the code here
    return __persistentStoreCoordinator;

    The highlighted lines are the one to be added. Please notice that row 8 needs to be updated with options:options. I only tried it using NSSQLiteStoreType as persistent store type but it should work fine even with NSXMLStoreType.


  1. Working with Core Data: Schema Versioning and Lightweight Migrations
  • Thanks for this, it worked right away.

    Maybe nice to tell how you set the active model version:

    Select the model Folder (and not the model file) in Xcode in the Project Navigator, and after that look for the Versioned Core Data Model tab in the File Inspector on the right, where you can set the model version you prefer.

    • elbryan

      Thank you!

  • Dennis Hempler

    That’s how you do a tutorial!