This tutorial is presented as part of our iOS 11 Launch Party — enjoy! When you create a Core Data app, you design an initial data model for your app. What do you do then? The migration process will update data created with a previous version of the data model to match the current data model. Let the great migration begin! When to Migrate When is a migration necessary? If an app is using Core Data merely as an offline cache, when you update the app, you can simply delete and rebuild the data store.
The Migration Process When you initialize a Core Data stack, one of the steps involved is adding a store to the persistent store coordinator. When you encounter this step, Core Data does a few things prior to adding the store to the coordinator. To start the migration process, Core Data needs the original data model and the destination model.
It uses these two versions to load or create a mapping model for the migration, which it uses to convert data in the original store to data that it can store in the new store. Once Core Data determines the mapping model, the migration process can start in earnest. Migrations happen in three steps: First, Core Data copies over all the objects from one data store to the next. Next, Core Data connects and relates all the objects according to the relationship mapping.
Finally, enforce any data validations in the destination model. Core Data disables destination model validations during the data copy. Only when a migration is successful, will Core Data remove the original data store. This happens automatically when you use NSPersistentContainer, or you have to set some flags when building your own Core Data stack.
Manual Migrations Manual migrations involve a little more work on your part. Setting up a mapping model in Xcode is much like setting up a data model, with similar GUI tools and some automation. Custom Manual Migrations This is level 3 on the migration complexity index. Custom entity transformation logic involves creating an NSEntityMigrationPolicy subclass and performing custom transformations there. Custom version detection logic and custom handling of the migration process are necessary.
Unzip it and open it in Xcode. Build and run the app in the iPhone simulator. Add a title there is default text in the note body to make the process faster and tap Create to save the new note to the data store.
Repeat this a few times so you have some sample data to migrate. The data model is simple — just one entity, a Note, with a few attributes. But you already added a few test notes in the app. How can you change the model without breaking the existing notes? This will show you the Entity Modeler in the main work area.
Next, open the Editor menu and select Add Model Version…. Xcode will now create a copy of the data model. You can give this file any name you want. The sequential v2, v3, v4, et cetera naming helps you easily tell the versions apart. This step will create a second version of the data model, but you still need to tell Xcode to use the new version as the current model. In order to perform any migration, you want to keep the original model file as it is, and make changes to an entirely new model file.
In the File Inspector pane on the right, there is a selection menu toward the bottom called Model Version. Core Data will try to first connect the persistent store with the ticked model version when setting up the stack.
The older version is there to support migration. The current model is the one Core Data will ensure is loaded prior to attaching the rest of the stack for your use. Make sure you have the v2 data model selected and add an image attribute to the Note entity. Just such a transformer has been provided for you in ImageTransformer.
Next, in the Module field, choose Current Product Module. The new model is now ready for some code! Build and run the app. It turns out lightweight migrations are enabled by default. This means every time you create a new data model version, and it can be auto migrated, it will be.
What a time saver! Core Data can automatically look at the differences in two data models and create a mapping model between them. For entities and attributes that are identical between model versions, this is a straightforward data pass through mapping. For other changes, just follow a few simple rules for Core Data to create a mapping model.
In the new model, changes must fit an obvious migration pattern, such as: Deleting entities, attributes or relationships Renaming entities, attributes or relationships using the renamingIdentifier Adding a new, optional attribute Adding a new, required attribute with a default value Changing an optional attribute to non-optional and specifying a default value Changing a non-optional attribute to optional Changing the entity hierarchy Adding a new parent entity and moving attributes up or down the hierarchy Changing a relationship from to-one to to-many Changing a relationship from non-ordered to-many to ordered to-many and vice versa Note: As a rule of thumb, all migrations, if necessary, should start as lightweight migrations and only move to more complex mappings when the need arises.
This means Core Data can easily migrate the old data store to a new one, since this change follows item 3 in the list of lightweight migration patterns. Image Attachments Now the data is migrated, you need to update the UI to allow image attachments to new notes. Luckily, most of this work has been done for you.
The Create Note scene is attached to a navigation controller with a root view controller relationship. Control-drag from the navigation controller to the Create Note With Images scene and select the root view controller relationship segue. This will disconnect the old Create Note scene and connect the new, image-powered one instead: Build and run, and choose to add a new note: Tap the Attach Image button to add an image to the note. Thankfully, the iOS 11 Simulator comes with a library of photos ready for your use.
The existing code uses the photo album, since there is no camera in the Simulator. Where to Go From Here? You can download the final project from this tutorial here. The full chapter in the Core Data by Tutorials book follows up this Core Data migrations tutorial with a series of more complex migrations. This chapter covers the basics of setting up your data model and then adding and fetching records.
This chapter will teach you how you customize your own managed object subclasses to store and validate data. Chapter 3, The Core Data Stack: Under the hood, Core Data is made up of many parts working together. Chapter 4, Intermediate Fetching: Your apps will fetch data all the time, and Core Data offers many options for getting the data to you efficiently.
This chapter covers more advanced fetch requests, predicates, sorting and asynchronous fetching. Table views are at the core of many iOS apps, and Apple wants to make Core Data play nicely with them! Chapter 6, Versioning and Migration: As you update and enhance your app, its data model will almost certainly need to change. Chapter 7, Unit Tests: Chapter 8, Measuring and Boosting Performance: Chapter 9, Multiple Managed Object Contexts: To enter, simply retweet this post using the ios11launchparty hashtag by using the button below: