Database Reference
In-Depth Information
Now build and run UnCloudNotes, and the data should migrate properly. Again,
your notes will be there, images and all, but you're now future-proof and ready to
add video, audio and anything else!
Migrating non-sequential versions
Thus far, you've walked through a series of data migrations in order. You've
migrated the data from version 1 to 2 to 3 to 4, in sequence. Inevitably, in the real
world of App Store launches, a user might skip an update and need to go from
version 2 to 4, for example. What happens then?
When Core Data performs a migration, its intention is to perform only a single
migration. In this hypothetical scenario, Core Data would look for a mapping model
that goes from version 2 to 4; if one didn't exist, Core Data would infer one, if you
tell it to. Otherwise the migration will fail, and Core Data will report an error when
attempting to attach the store to the persistent store coordinator.
How can you handle this scenario? You could provide multiple mapping models, but
as your app grows, you'd need to provide an inordinate number of these: from v1
to v4, v1 to v3, v2 to v4, et cetera. You would spend more time on mapping models
than on the app itself!
The solution to this scenario is to implement a fully custom migration sequence.
You already know that the migration from version 2 to 3 works; to go from 2 to 4,
it will work well if you manually migrate the store from 2 to 3 and then from 3 to 4.
This step-by-step migration means you'll prevent Core Data from looking for a
direct 2 to 4 or even a 1 to 4 migration.
A self-aware stack
To begin implementing this solution, you'll want to create a separate “migration
manager” class. The responsibility of this class will be to provide a properly
migrated Core Data stack, when asked. That is, this class will have a stack property
and will return an instance of CoreDataStack , as UnCloudNotes uses throughout,
which has run through all the migrations necessary to be useful for the app.
First, create a new Swift file called DataMigrationManager. Open the file and
replace its contents with the following:
import Foundation
import CoreData
class DataMigrationManager {
let storeName: String
let modelName: String
var options: NSDictionary ?
var stack: CoreDataStack !
 
Search WWH ::




Custom Search