Lightweight Migration

Core Data

Core Data is a framework developed and maintained by Apple.Core Data is the M in MVC, the model layer of your application. Even though Core Data can persist data to disk, data persistence is actually an optional feature of the framework. Core Data is first and foremost a framework for managing an object graph.Core Data is not a database and that it manages your application’s object graph.

Core Data Manages an Object Graph :

Remember that Core Data is first and foremost an object graph manager. To understand what that means, you need to know what an object graph is.An object graph is nothing more than a collection of objects that are connected with one another. The Core Data framework excels at managing complex object graphs.

The Core Data framework takes care of managing the life cycle of the objects in the object graph. It can optionally persist the object graph to disk and it also offers a powerful interface for searching the object graph it manages.But Core Data is much more than that. The framework adds a number of other compelling features, such as input validation, data model versioning, and change tracking.Even though Core Data is a perfect fit for a wide range of applications, not every application should use Core Data.

Migrating a Data Model With Core Data :

An application that grows and gains features also gains new requirements. The data model, for example, grows and changes. Core Data handles changes pretty well as long as you play by the rules of the framework.

When you release an app and add new features, there will be a time you need to update you persistent store. This is easy to do when you are in a development stage, because you can just delete your app and the persistent store will be re-generated. But when you are live and people have downloaded your app, you need to be careful. They won’t like it if suddenly their saved data has disappeared!

It isn’t very hard to do, because Core Data is pretty smart to do lightweight migrations as long as your changes comply to a few rules. For more complex migrations you can setup a mapping model!The steps

Is it a lightweight migration?

You need to be sure that what you are going to change to your data model is actually a lightweight migration? These are the rules:

    • Add an entity
    • Remove an entity
    • Rename an entity
    • Add an attribute / relationship
    • Remove an attribute / relationship
    • Rename an attribute / relationship
    • Make an attribute / relationship optional
    • Make an attribute / relationship not optional, but provide a default value!

So if your model changes comply to these rules, you are good to go for a lightweight migration. If not, you have to setup a mapping model!
Create a new version of your model
Every time you update something in your model, you need to create a new version.

Go to Editor

 < Add model version and follow the wizard.

You can now do the changes in the new model.

Use the new model

The current data model being used is being marked with the little green check icon.
Currently your old model will still be active.
To change this, just click on the top level data model (Sample.xcdatamodeld in the example) and go to your File inspector. In the Versioned Core Data Model section, you can select the new model from the drop down list.

The migration code

The last step is to tell the persistent store that you want to perform a lightweight migration.
Go to your AppDelegate persistentStoreCoordinator setter function and create a dictionary with 2 keys and set them to YES

  • NSMigratePersistentStoresAutomaticallyOption
  • NSInferMappingModelAutomaticallyOption

Managing Changes to Entities and Properties

If you rename an entity or property, you can set the renaming identifier in the destination model to the name of the corresponding property or entity in the source model. Use the Xcode Data Modeling tool’s property inspector (for either an entity or a property) to set the renaming identifier in the managed object model. For example, you can:

    • Rename a Car entity to Automobile

Rename a Car’s color attribute to paintColor

The renaming identifier creates a canonical name, so set the renaming identifier to the name of the property in the source model (unless that property already has a renaming identifier). This means you can rename a property in version 2 of a model, then rename it again in version 3. The renaming will work correctly going from version 2 to version 3, or from version 1 to version 3.

Managing Changes to Relationships

Lightweight migration can also manage changes to relationships and to the type of relationship. You can add a new relationship or delete an existing relationship. You can also rename a relationship by using a renaming identifier, just like an attribute.

In addition, you can change a relationship from a to-one to a to-many, or a nonordered to-many to an ordered (and vice versa).
Managing Changes to Hierarchies
You can add, remove, and rename entities in the hierarchy. You can also create a new parent or child entity and move properties up and down the entity hierarchy. You can move entities out of a hierarchy. You cannot, however, merge entity hierarchies; if two existing entities do not share a common parent in the source, they cannot share a common parent in the destination.

Confirming Whether Core Data Can Infer the Model

If you want to determine in advance whether Core Data can infer the mapping model between the source and destination models without actually doing the work of migration, you can use NSMappingModel’s inferredMappingModelForSourceModel:destinationModel:error: method. The method returns the inferred model if Core Data is able to create it; otherwise, it returns nil.
If your data change exceeds the capabilities of automatic migration, you can perform a heavyweight migration (often referred to as manual migration).

Requesting Lightweight Migration

You request automatic lightweight migration using the options dictionary that you pass into addPersistentStoreWithType:configuration:URL:options:error:. Set values corresponding to both the NSMigratePersistentStoresAutomaticallyOption and the NSInferMappingModelAutomaticallyOption keys to YES:

Eg :
NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom];
NSDictionary *options = @{NSMigratePersistentStoresAutomaticallyOption: @YES, NSInferMappingModelAutomaticallyOption: @YES};
NSError *error = nil;
if (![psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {
NSAssert(NO, @"Unable to load persistent store: %@\n%@", [error localizedDescription], [error userInfo]);
}

With these settings in place, Core Data will attempt a lightweight migration when it detects the persistent store no longer matches the current model

Author :Srinivasa Rao Polisetty – iOS Developer
Source :wikipedia and developer.apple.com