Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Entity to Core Data

We have an app that uses Core Data. In the next version I would like to add a new Entity to the already existing Entities.

Is ok just to add the new one and then populate it from the software, or is there something that I have to think about?

like image 212
Jorgen Avatar asked Dec 04 '22 19:12

Jorgen


1 Answers

There's a couple of types of migration. The easiest is lightweight migration with an inferred mapping model — what that means is that you just tell it to do a migration and the software handles the rest. The caveat, however, is that it can only cope with certain kinds of changes. Adding an entity should be OK.

To enable lightweight migration, you need to pass in a few options when opening your persistent store:

NSMutableDictionary *options = [[NSMutableDictionary alloc] init];
[options setObject:[NSNumber numberWithBool:YES] forKey:NSMigratePersistentStoresAutomaticallyOption];
[options setObject:[NSNumber numberWithBool:YES] forKey:NSInferMappingModelAutomaticallyOption];

 NSError *error = nil;
__persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error])
{
   NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
}    

The one final thing to do is when making the change to your data model, you need to add a model version. In Xcode 4, select your data model in the sidebar, choose Add Model Version from the Editor menu, and name your new version. Then you need to set the new version as the active one: choose your main data model file from the left sidebar again, and then in the right sidebar, first tab, there should be a "Versioned Data Model" popup menu.

This is very important. To do a migration, Core Data needs the version of your model that the old store was created with, as well as the version you want to migrate to. If you don't have the old version, migration will fail.

like image 58
Amy Worrall Avatar answered Dec 31 '22 22:12

Amy Worrall