Josue Espinosa
Josue Espinosa

Reputation: 5089

Save Core Data?

I have a functional app that is largely database oriented. My client is currently using the app and it has lots of pre-existing saved data (note: it is all local, not saved on an online database). Problem is, I know when I update my data model, I will have to uninstall, then reinstall the application because otherwise it will crash due to inconsistencies in the data model. Is there any way to save the data there while still updating my data model?

Upvotes: 0

Views: 96

Answers (1)

Tom Harrington
Tom Harrington

Reputation: 70946

I know when I update my data model, I will have to uninstall, then reinstall the application because otherwise it will crash due to inconsistencies in the data model.

Not true, not unless you just don't bother to deal with the change. Core Data includes support for migrating data from one version of a data model to a newer one, so that existing data stores get updated to use the new model without uninstalling or other extreme steps. In most cases it's even automatic-- you just have to tell it to deal with the change. Specifically, use the options parameter when adding the persistent store:

NSDictionary *options = @{NSMigratePersistentStoresAutomaticallyOption:@YES,
    NSInferMappingModelAutomaticallyOption:@YES};


if (![psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {
    ....
}

That works if your changes include only one or more of the following:

  • Adding or removing an attribute
  • Changing an attribute's "optional" flag (provided that if you're making it non-optional, you provide a default value)
  • Renaming an entity or an attribute
  • Adding, removing, or renaming entities
  • Adding parent or child entities, or moving attributes to a different point in the hierarchy
  • Changing a relationship from to-one to to-many

If you're renaming anything, you need to set the renaming identifier so that Core Data knows how to migrate.

If that's not enough, Core Data supports non-automatic migration in a couple of different ways. That's covered in some detail in Apple's documentation, which I won't try to reproduce here.

Upvotes: 3

Related Questions