Skip to main content

When working with any database, migrating from one version of a schema to another is a pain. I’ve yet to come across a framework that offers a migration feature that is a joy to work with, but until recently I’d never had to work with Core Data migrations. I didn’t know how lucky I had it. This stuff is complicated.

Thankfully I found some great resources which helped me get my head around the whole thing. I’ve linked to them below – I’m sure I’ll be using them again to refresh my memory at some point, and maybe they’ll help someone else avoid spending the day Googling as I did.

1. https://pragprog.com/book/mzcd2/core-data
(Core Data by Marcus S. Zarra is a great resource. I have a copy and I’ve found it more useful than any other iOS development book I own)
2. http://stackoverflow.com/questions/25285068/core-data-mixing-lightweight-and-custom-migration
3. http://www.artandlogic.com/blog/2013/07/iterative-core-data-migrations
4. http://www.objc.io/issue-4/core-data-migration.html
5. https://github.com/alo7/ALO7ProgressiveMigrationManager

Links 2-5 are concerned with making migration as painless as possible, which was my focus. Core Data offers ‘lightweight’ and ‘heavyweight’ migration types. The former makes use of Core Data’s ability to infer model schema changes automatically, while the latter requires the developer to manage multiple mapping files and write complicated, verbose policy classes to manually shuttle data around. Apple themselves recommend that developers take advantage of lightweight migrations whenever possible, such is the difference in performance between the two types.

The latter three links discuss an iterative/progressive approach that was first suggested in Zarra’s book. This drastically reduces the number of these files we need to create. Regardless of which version of the schema the user started with and which version we need to get them to, we have a linear upgrade path, which is much easier to predict and write code for. They also provide concrete examples which I found very useful – this topic is conceptually complex, and seeing things laid out in code helped me visualise what happens at runtime when a migration needs to be run. This progressive approach to migration is the one we’re taking in the app.