Implementation of “Automatic Lightweight Migration” for Core Data (iPhone)

This is what I did to make Automatic Lightweight Migration (Source:

1. Set the Persistent Store options for automatic migration in the app delegate.

Change your persistentStoreCoordinator creation to this (replace YOURDB):

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

  if (persistentStoreCoordinator != nil) {
    return persistentStoreCoordinator;

  NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"YOURDB.sqlite"]];

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

  NSError *error = nil;
  persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];
  if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error]) {
    // Handle error

  return persistentStoreCoordinator;

2. Version your Data Model and Edit the new file.

Select your xcdatamodel file
Design -> Data Model -> Add Model Version (expand your xcdatamodeld item)
Select the “2″ (or later) file, Design -> Data Model -> Set Current Version (edit this version)

3. Specify the momd resource in app delegate.

Change your managedObjectModel implementation to this (replace YOURDB)

- (NSManagedObjectModel *)managedObjectModel {

  if (managedObjectModel != nil) {
    return managedObjectModel;

  NSString *path = [[NSBundle mainBundle] pathForResource:@"YOURDB" ofType:@"momd"];
  NSURL *momURL = [NSURL fileURLWithPath:path];
  managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:momURL];

  return managedObjectModel;

Leave a Comment