Why Does CoreData crash when I add an Attribute?
there is a way, and this way is called automatic lightweight migration. It needs a codechange and an extra step when changing your object model.
For the code you have to add two options to the method where you initialize your persistent store coordinator. something like this:
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (persistentStoreCoordinator_ != nil) {
return persistentStoreCoordinator_;
}
NSString *storePath = [AppDelegate_Shared coredataDatabasePath];
NSURL *storeURL = [NSURL fileURLWithPath:storePath];
// important part starts here
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,
nil];
NSError *error = nil;
persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![persistentStoreCoordinator_ addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {
// and ends here
LogError(@"Unresolved error %@, %@", error, [error userInfo]);
// Do something
}
return persistentStoreCoordinator_;
}
Now if you want to change your model, you have to create a model version before you do any changes.
Select your datamodel, and go into the main menu Design -> Data Model -> Add Model Version
. Your "old" model will be renamed and you make your changes in the current model, the one with the green mark.
All the old models are kept and will be put into your application, so your app can perform the 'automatic lightweight migration' and upgrade the existing database to your new model.