Search code examples
objective-ccocoamacoscore-datamapping-model

CoreData customize mapping model


I have a problem mapping the following situation from v1 to v2 of a core data model.

In v1 of the model I had an entity named book with an attribute author. There I saved the first and last name of the author and even first and last names of several authors. Very poor design I know, but that's how it was.

In v2 of the model I made it better and added the entity author with the attributes firstname and lastname and a relationship to book. Does anyone know out there how I can customize the mapping model in such a manner, that it calls a function (which returns the number of authors and the first and last name separated) and creates the new entities regarding to the output of that function?

Thanks b00tsy


Solution

  • You start off by creating a mapping model between the source and destination models. From there you want to select the object in the mapping model that you are going to want to handle this split. On the right side of the mapping model editor you will see where you can name a class that is the NSEntityMigrationPolicy. By adding a custom mapping policy class here you can tell the migration to use your code instead of the standard code.

    From there, create the class and have it subclass NSEntityMigrationPolicy. Inside of that class override the method -createDestinationInstancesForSourceInstance: entityMapping: manager: error:. This method will be called once per object and it is your responsibility to create the destination object and copy all of the attributes from the source to the destination. As part of that copy you can split the name into first name and last name by however logic you feel is appropriate. At the end of that method make sure you call -associateSourceInstance: withDestinationInstance: forEntityMapping: so that the NSMigrationManager is aware of the newly created destination object and the rest of the migration will work correctly.

    NOTE: you do not need to override any of the relationship related methods unless you need to write custom code for those as well.

    That is all there is to it.