Search code examples
ioscore-datacore-data-migration

Core Data Migration - Migrating selected data from a previous version


We're performing our first iOS app update, and also our first Core Data migration.

It seems more complicated than the examples of the Standard and Lightweight Core Data migrations i've seen online, but perhaps i'm missing something.

Our scenario is that we've updated the .xcdatamodel (simply added a new field), and also a lot of the reference data used in our app (stored in our Core Data database), but we need to retain some user data (stored in the same Core Data database).

I've added multiple versions of the model definition into our .xcdatamodelld file, and have played around with a Lightweight Core Data migration process (using a Mapping Model (an .xcmappingmodel file)), which successfully updates the model, but I can't see any obvious way in which it would allow us to import selected data (the user's data) from a previous version of the database into a new one bundled with the next version of the app (containing our updated reference data).

Any advice on how to approach this scenario would be very much appreciated.

Thanks in advance, Ted


Solution

  • In the end we've worked around this situation by putting the user's data into a plist file (there's a fairly limited amount of this), and retaining the Core Data database to use solely for reference data in the system, so it can be overwritten in future without worry.

    A lightweight migration updates the data model on first run, and then a one off migration call creates and populates the user data plist file, renames the v1 core data persistent store *_migrated.sqlite, copies the v2 sqlite database from the bundle into the documents dir, then resets the MOM, and sets the MOM, MOC and Persistent Store to nil, so that the next time Core Data starts it uses the v2 sqlite database as its Persistent Store.

    Phew. I hope this makes some sense to anyone reading it, feel free to ask for any other details, but it was honestly a lot simpler than it all sounds!