core data migration

12
Core Data Migration Strategies

Upload: monica-kurup

Post on 04-Aug-2015

338 views

Category:

Software


0 download

TRANSCRIPT

Core Data Migration Strategies

Core Data

What is Core Data?

Model layer of application in Model-View-Controller pattern.

Core data is not database nor an API for persisting data to database.

Framework that manages an object graph.

Core Data Stack

Collection of objects.

Key objects of the stack are:

NSManagedObjectModel

NSPersistentStoreCoordinator

NSManagedObjectContext

NSManagedObjectModel

Data model of the application.

Schema of a database.

Contains information about the entities or model in the object graph, their attributes and relationships between them.

NSPersistentStoreCoordinator

Persist data to disk.

Ensures persistent store and data model are compatible.

Mediates between persistent store and managed object context.

Takes care of loading and caching of data.

NSManagedObjectContext

Manages collection of model objects.

Used for inserting, deleting and fetching objects from database.

Backed by NSPersistentStoreCordinator.

Core Data Migration Strategies

Automatic Lightweight Migration:

1. Enable automatic migration in persistent store coordinator

NSDictionary *options = [ NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithBool: YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool: YES], NSInferMappingModelAutomaticallyOption, nil];

[persistentStoreCoordinator addPersistentStoreWithType: NSSQLiteStoreType configuration:nil url: storeUrl options: options error:&error];

2. Version data model & edit new file

• Select Xcdatamodel file -> Editor -> Add model version

• Select “2”file or later, design -> set current version (edit this version)

3. Specify the momd resource in app delegate

• NSString *path= [[NSBundle mainBundle]pathForResource: @”YOURDBPATH” ofType:@”momd”];

• NSURL *momUrl=[ NSURL fileURLWithPath: path];

• managedObjectModel =[ [NSManagedObjectModel alloc]initWithContentsOfURL : momURL];

Custom core data Migrations Mapping Model:

• Needs source & destination data model

• NSMigrationManager infer mapping model between two models.

• Large complexity.

• Version 1 -> version 2, what if user has version 1 and now want to install version 3; you don’t have version 1 -> version 3

Progressive Migration:

• Create one mapping model for each consecutive data model

• Version 1 -> version 2

• Version 2 -> version 3 and so on.

Thanks.