iOS Core Data Migration
Part 1 – Lightweight migration in three simple steps
Disclaimer: The content of this blog are my views, observations and understanding about the topic based on my personal experience.
What is core data?
Core data is used to add offline capabilities to an iOS application. You can store permanent data or cache temporary data to boost the performance of an app by reducing the number of API calls to the server.
When does migration come into the picture?
As the application evolves in terms of features, there comes a need to add or update entities/attributes and their relations in the existing data model. So, after you plan to update the data model, users that are already using your application need to migrate to this updated data model.
Which type of migration suits you?
The types of migration, either lightweight or heavyweight, is decided on the types of changes you make to the data model.
Below are the changes that could be handled by the lightweight migration:
- Addition of an attribute
- Removal of an attribute
- A non-optional attribute becoming optional
- An optional attribute becoming non-optional and defining a default value
- Renaming an entity or property
Let’s begin with the migration:
Step 1: Create a new version of your data model
- Start by selecting Editor > Add Model Version…
- Name the current version of the data model
- Expand your data model file to view all available versions of the data model, and select the newly created data model as the model to be currently used. The green checkmark next to the file name indicated the data mode currently being used.
Step 2: Make the necessary changes to the newly created data model
Step 3: Set “NSMigratePersistentStoresAutomaticallyOption” and“NSInferMappingModelAutomaticallyOption” to true
Add the code below where your NSPersistentStoreCoordinator is created. It is mostly in the AppDelegate.m class if you haven’t created a separate class to manage core data operations.
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMgratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
Pass this dictionary to options parameter of addPersistentStoreWithType:configuration:URL:options:error: method.
So that’s it! You have completed the migration process. Try running the application.
For further information about core data, you can refer to the official documentation from Apple.