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.
(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)
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.