- Changing a Managed Object Model
- Adding a Model Version
- Lightweight Migration
- Default Migration
- Migration Manager
- Summary
- Exercises
Adding a Model Version
To avoid the crash previously demonstrated in Figure 3.1, you’ll 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 older 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 Grocery Dude 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 will start out as a replica of Model.xcdatamodel. This 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 wish to get into the habit of taking a snapshot, or even backing up the whole project prior to editing a model.
Update Grocery Dude as follows to reintroduce the Measurement entity:
- Optionally take a snapshot or back up the Grocery Dude project.
- Select Model 2.xcdatamodel.
- Create a new entity called Measurement.
- Select the Measurement entity, create an attribute called abc, and then set its type to String.
After you’ve added the new model version, you still need to set it as the current version before it will be used by the application.
Update Grocery Dude as follows to change the current model version:
- Select Model.xcdatamodeld.
- Click View > Utilities > Show File Inspector (or press Option+⌘+1).
- Set the Current Model Version to Model 2, as shown in Figure 3.3.
Figure 3.3 Setting the current model
Before you can successfully launch the application, you’ll need to configure migration options to tell Core Data how to migrate. Feel free to launch it again to generate the “Store is incompatible” error in the meantime.