Adding Entity to Core Data

2020-07-18 09:41发布

问题:

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?

回答1:

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.



回答2:

Changing the model is a difficult task. In theory it should be easy to just add an entity, but Apple built in a migration tool for the task. (This is in case you change the structure of existing data)

I have migrated Core Data databases before, but on MAC OS and it was over 2 years ago.

Here is the guide

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreDataVersioning/Introduction/Introduction.html