- Changing a Managed Object Model
- Adding a Model Version
- Lightweight Migration
- Default Migration
- Migration Manager
- Summary
- Exercises
Adding a Model Version
To avoid the error shown in Figure 3.1, you need to create a new model version before making changes to the model. Ongoing, you should not remove old versions of a model. Old model versions are needed to help migrate incompatible persistent stores to the current model version. If there are no existing persistent stores on customer devices, you can ignore model versioning until your application is on the App Store.
Update Groceries as follows to add a model version:
- Select Model.xcdatamodeld.
- Click Editor > Add Model Version....
- Click Finish to accept Model 2 as the version name.
You should now have two model versions, as shown in Figure 3.2.
Figure 3.2 Multiple model versions
The new model Model 2.xcdatamodel starts out as a replica of Model.xcdatamodel. This unfortunately makes it easy to modify the wrong version unintentionally. Before you edit a model, you should triple-check you have selected the correct one. You may want to get into the habit of taking a snapshot, committing to source control, or even backing up the whole project prior to editing a model. Note that the check mark in the green circle represents the current model, which is the model version used at runtime.
Update Groceries as follows to reintroduce the Measurement entity:
- Optionally take a snapshot or back up the Groceries project.
- Select Model 2.xcdatamodel.
- Add a new entity and rename it to Measurement.
- Select the Measurement entity and add an attribute called abc. Set its type to String.
After you add the new model version, you still need to set it as the current version before it is used by the application.
Update Groceries as follows to change the current model version:
- Select Model.xcdatamodeld (not Model.xcdatamodel).
- Click View > Utilities > Show File Inspector (or press Option++1).
- Set the Current Model Version to Model 2, as shown at the bottom of Figure 3.3.
Figure 3.3 Setting the current model
Before you can successfully launch the application, you need to configure migration options to tell Core Data how to migrate. Feel free to launch it again to generate the incompatible store error in the meantime.