4

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 ?

Ben
  • 761
  • 1
  • 12
  • 35
  • Please update your original question with new details rather than creating a duplicate. – Wain Sep 08 '16 at 15:22
  • 2
    Possible duplicate of [Core Data: Add a column on a table](http://stackoverflow.com/questions/39370797/core-data-add-a-column-on-a-table) – Wain Sep 08 '16 at 15:22

2 Answers2

21

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

enter image description here

Ron Diel
  • 1,354
  • 7
  • 10
  • 1
    Don't do this if you sync CoreData with CloudKit! CloudKit does not allow the renaming of fields. So you'd need to create new fields rather than rename old ones. For everyone else, this is a great and easy option. – Daniel Oct 21 '22 at 09:59
-1

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.

Tom Harrington
  • 69,312
  • 10
  • 146
  • 170
  • 1
    Renaming is fully supported by Apple's lightweight migration process as long as you don't sync CoreData with CloudKit. For further details see also https://developer.apple.com/documentation/coredata/using_lightweight_migration for further details. – Morpheus78 Jul 14 '21 at 21:44