问题
I just want to rename and add attribute on my table for a new version of my app and I want to keep the data if the app was already installed.
Firstly I just set the options:
let options = [NSMigratePersistentStoresAutomaticallyOption:true, NSInferMappingModelAutomaticallyOption:true]
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: options)
And I created a new version model, so if I rename the attributes and add another attributes to my table on the new model, do the app gonna keep the data ?
回答1:
Per Apple's Core Data Versioning and Migration Guide's section on Lightweight Migrations:
If you rename an entity or property, you can set the renaming identifier in the destination model to the name of the corresponding property or entity in the source model. You set the renaming identifier in the managed object model using the Xcode Data Modeling tool’s property inspector (for either an entity or a property). For example, you can: ... Rename a Car’s color attribute to paintColor
回答2:
Your code requests automatic lightweight migration. If you want to rename an attribute, migrating like that will not retain data for that attribute. All other data will be retained. Core Data would see it as deleting the old attribute and adding a new unrelated attribute.
If you want to rename an attribute and retain data for that attribute, you can't use automatic lightweight migration. You would need to create a mapping model to tell Core Data how to migrate the data-- specifically, to tell it that the data from the old attribute name should move to using the new attribute name. Once you have more than one version of the mode, you can create a mapping model in Xcode to set this up. The overall process is described in Apple's guide to model migration.
来源:https://stackoverflow.com/questions/39391719/core-data-rename-attribute-without-having-issues-with-users-and-their-current-d