Archive for July, 2012

Core Data Model Mapping

July 2, 2012

Here is the basic process for migrating from one Data Model to a bother in Core Data between versions.   When you need to drastically change the ERD.    The original question this is in response to is here:

http://stackoverflow.com/questions/11174773/migrating-a-many-to-many-relationship-to-a-join-table-in-core-data

1. Create a versioned copy of the Data Model. (Select the Model, then Editor->Add Model Version)

2. Make your changes to the new copy of the data model

3. Mark the copy of the new data model as the current version. (Click the top level xcdatamodel item, then in the file inspector set the “Current” entry under “Versioned Data Model” section to the new data model you created in step 1.

4. Update your model objects to add the RecipeIngredient entity. Also replace the ingredients and recipes relationships on Recipe and Ingredient entities with new relationships you created in step 2 to the RecipeIngredient Entity. (Both entities get this relation added. I called mine recipeIngredients) Obviously wherever you create the relation from ingredient to recipe in the old code, you’ll now need to create a RecipeIngredient object.. but that’s beyond the scope of this answer.

5. Add a new Mapping between the models (File->New File…->(Core Data section)->Mapping Model. This will auto-generate several mappings for you. RecipeToRecipe, IngredientToIngredient and RecipeIngredient.

6. Delete the RecipeIngredient Mapping. Also delete the recipeIngredient relation mappings it gives you for RecipeToRecipe and IngredientToRecipe (or whatever you called them in step 2).

7. Drag the RecipeToRecipe Mapping to be last in the list of Mapping Rules. (This is **important** so that we’re sure the Ingredients are migrated before the Recipes so that we can link them up when we’re migrating recipes.) The migration will go in order of the migration rule list.

8. Set a Custom Policy for the RecipeToRecipe mapping “DDCDRecipeMigrationPolicy” (This will override the automatic migration of the Recipes objects and give us a hook where we can perform the mapping logic.

9. Create DDCDRecipeMigrationPolicy by subclassing NSEntityMigrationPolicy for Recipes to override createDestinationInstancesForSourceInstance (See Code Below). This will be called once for Each Recipe, which will let us create the Recipe object, and also the related RecipeIngredient objects which will link it to Ingredient. We’ll just let Ingredient be auto migrated by the mapping rule that Xcode auto create for us in step 5.

10. Wherever you create your persistent object store (probably AppDelegate), ensure you set the user dictionary to auto-migrate the data model:

if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType

configuration:nil
URL:storeURL
options:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, nil]
error:&error])
{
}

**Subclass NSEntityMigrationPolicy for Recipes**

#import <CoreData/CoreData.h>

@interface DDCDRecipeMigrationPolicy : NSEntityMigrationPolicy
@end

**Override createDestinationInstancesForSourceInstance in DDCDRecipeMigrationPolicy.m **

<!– language: lang-c –>

– (BOOL)createDestinationInstancesForSourceInstance:(NSManagedObject *)sInstance entityMapping:(NSEntityMapping *)mapping manager:(NSMigrationManager *)manager error:(NSError **)error
{

NSLog(@”createDestinationInstancesForSourceInstance : %@”, sInstance.entity.name);

//We have to create the recipe since we overrode this method.
//It’s called once for each Recipe.
NSManagedObject *newRecipe = [NSEntityDescription insertNewObjectForEntityForName:@”Recipe” inManagedObjectContext:[manager destinationContext]];
[newRecipe setValue:[sInstance valueForKey:@”name”] forKey:@”name”];
[newRecipe setValue:[sInstance valueForKey:@”overview”] forKey:@”overview”];
[newRecipe setValue:[sInstance valueForKey:@”instructions”] forKey:@”instructions”];

for (NSManagedObject *oldIngredient in (NSSet *) [sInstance valueForKey:@”ingredients”])
{
NSFetchRequest *fetchByIngredientName = [NSFetchRequest fetchRequestWithEntityName:@”Ingredient”];
fetchByIngredientName.predicate = [NSPredicate predicateWithFormat:@”name = %@”,[oldIngredient valueForKey:@”name”]];

//Find the Ingredient in the new Datamodel. NOTE!!! This only works if this is the second entity migrated.
NSArray *newIngredientArray = [[manager destinationContext] executeFetchRequest:fetchByIngredientName error:error];

if (newIngredientArray.count == 1)
{
//Create an intersection record.
NSManagedObject *newIngredient = [newIngredientArray objectAtIndex:0];
NSManagedObject *newRecipeIngredient = [NSEntityDescription insertNewObjectForEntityForName:@”RecipeIngredient” inManagedObjectContext:[manager destinationContext]];
[newRecipeIngredient setValue:newIngredient forKey:@”ingredient”];
[newRecipeIngredient setValue:newRecipe forKey:@”recipe”];
NSLog(@”Adding migrated Ingredient : %@ to New Recipe %@”, [newIngredient valueForKey:@”name”], [newRecipe valueForKey:@”name”]);
}

}

return YES;

}

 

This should look like this in Xcode when you’re done:

Also note that the Xcode Core Data model mapping stuff is a bit flaky and occasionally needs a “clean”, good Xcode rester, simulator bounce or all of the above get it working.