Database Reference
In-Depth Information
}
This method takes the store URL, a source model, destination model and an
optional mapping model. If you need to do a lightweight migration, you can pass
nil or simply skip the final parameter.
Here's what's going on, step by step:
1. First, you create an instance of the migration manager.
2. If a mapping model was passed in to the method, then you use that. Otherwise,
you create an inferred mapping model.
3. Since migrations will create a second data store and migrate data, instance-by-
instance, from the original to the new file, the destination URL must be a different
file. Now, the example code in this section will create a destinationURL that is the
same folder as the original and a file concatenated with “~1”. The destination URL
can be in a temp folder or anywhere your app has access to write files.
4. Here's where you put the migration manager to work! You've already set it up
with the source and destination models, so you simply need to add the mapping
model and the two URLs to the mix.
5. Given the result, you can print a success or error message to the console. In the
success case, you perform a bit of cleanup, too. In this case, it's enough to
remove the old store and replace it with the new store.
Now it's simply a matter of calling that method with the right parameters.
Remember your empty implementation of performMigration ? It's time to fill that in.
Add the following lines to that method:
if ! currentModel . isVersion4 () {
fatalError ( "Can only handle migrations to version 4!" )
}
You know the most recent version of the model, so this code bails out and kills the
app if the current model is anything other than version 4. This is a little extreme—in
your own apps, you might want to continue the migration anyway—but doing it this
way will definitely remind you to think about migrations if you ever add another
data model version to your app!
Add the next bit of code to the end of performMigration :
if let storeModel = self . storeModel {
if storeModel. isVersion1 () {
options =
[ NSMigratePersistentStoresAutomaticallyOption : true ,
NSInferMappingModelAutomaticallyOption : true ]
} else {
options =
[ NSMigratePersistentStoresAutomaticallyOption : true ,
Search WWH ::




Custom Search