iPhone Core Data "Automatic Lightweight Migration"
Solution 1:
To recap/Full guide:
-
Before making any change, create a new model version.
In Xcode 4: Select your
.xcdatamodel
-> Editor -> Add Model Version.In Xcode 3: Design -> Data Model -> Add Model Version.
You will see that a new
.xcdatamodel
is created in your.xcdatamodeld
folder (which is also created if you have none). Save.
Select your new
.xcdatamodel
and make the change you wish to employ in accordance with the Lightweight Migration documentation.Save.
-
Set the current/active schema to the newly created schema.
With the
.xcdatamodeld
folder selected:In Xcode 4: Utilities sidebar -> File Inspector -> Versioned Core Data Model -> Select the new schema.
In Xcode 3: Design > Data Model > Set Current Version.
The green tick on the
.xcdatamodel
icon will move to the new schema. Save.
-
Implement the necessary code to perform migration at runtime.
Where your
NSPersistentStoreCoordinator
is created (usually AppDelegate class), for theoptions
parameter, replacenil
with the following code:[NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil]
Run your app. If there's no crash, you've probably successfully migrated :)
When you have successfully migrated, the migration code (step 7) can be removed. (It is up to the developer to determine when the users of a published app can be deemed to have migrated.)
IMPORTANT: Do not delete old model versions/schemas. Core Data needs the old version to migrate to the new version.
Solution 2:
I figured it out.
Design > Data Model > Add Model Version
Solution 3:
For Googlers again, this is what you need to do (assuming you have already set up Lightweight Migration):
- Before making changes, Do Design -> Data Model -> Add Model Version (you will see that a new
.xcdatamodel
is created in your.xcdatamodeld
folder) - Save
- Make your change
- Save
- Run App
Step #1 is crucial for making this work. I ran into this problem because I had followed these steps to add a new field. That worked. I added a second new field, but forgot to "Add Model Version", and things blew up.