July 8, 2014
Have you ever made many changes to your Core Data model layer without first making a new model version? I recently did just that and wanted to document the easy steps to put your project back on track. First, there are two assumptions:
The Scenario: You have shipped a 1.0 version of your Core Data app, and the data model is
looking great. After making sure the launch goes smoothly, you've envisioned some great new
features for the next version and are so excited that you dive right into the
xcdatamodeld
file to start making the necessary model changes.
Things are great: the next version's code is compiling, the new features work as intended, and
you start to do some more extensive testing before wrapping it up. Unfortunately, as you test
the upgrade path from 1.0 to the new version, you crash as you hit code paths that
exercise the new model changes. Although your changes are compatible with Lightweight Migration,
it isn't triggered unless the version of the data model changes; thus, your store is still in
the structure of the 1.0 data model and blows up when it sees the newer entities, attributes, or
relationships.
The Fix: Source control to the rescue! The labor intensive fix is to revert to the 1.0
xcdatamodeld
file, version the data model in Xcode, and manually
apply the needed changes to the new version. This is decidedly error-prone if you forget a change.
Luckily the easy fix is a lot less work and 100% reliable:
xcdatamodeld
file somewhere outside of source
control.xcdatamodeld
file.xcdatamodeld
copy you saved in Step 1 to the file generated by
Step 3.If your changes didn't meet the requirements for Lightweight Migration, the above steps will still work, but there is an extra step after Step 5: