Search code examples
ioscore-datacore-data-migration

Core data migration - how to combine two entities into one


I have a old core data model with two entities:

First entity

FirstString has an attribute: string1 which is NSString

Second entity

SecondString has an attribute: string2 which is NSString

They have a one to many relationship: first entity <--->> second entity.

The new entity - "ComboEntity" - has one to one relationship with both first entity and second entity.

Now I have new core data model with new entity

ComboEntity has an attribute: fullString

Question:

How do I migrate the data and combine string 1 and string 2 into fullString?

Thanks!


Solution

  • You should use a custom mapping policy.

    1. Create a mapping model from old entity version to new entity version
    2. Change your code to use custom mapping policy instead of automatic
    3. Write a custom mapping policy class, see example below:

    @interface FullStringFromTwoStringsMappingPolicy : NSEntityMigrationPolicy
    
    - (NSString *)fullStringForMyEntity:(MyEntity *)myEntity;
    
    @end
    
    @implementation FullStringFromTwoStringsMappingPolicy
    
    - (NSString *)fullStringForMyEntity:(MyEntity *)myEntity
    {
        return [NSString stringWithFormat:@"%@ %@", myEntity.string1, myEntity.string2];
    }
    
    @end
    

    In your mapping model you write a value expression as shown in the screenshot. Instead of contactHashMD5 you'd have your fullString attribute instead.

    enter image description here

    Best regards,

    sven.