Dives
Dives

Reputation: 127

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!

Upvotes: 3

Views: 1720

Answers (2)

svena
svena

Reputation: 2779

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.

Upvotes: 2

MrTJ
MrTJ

Reputation: 13202

CoreData model versioning has extensive support on iOS. Basically you need to create a new version of your model and create the new entity in that (possibly leaving also the old entities). Then, depending on your need, you can choose different levels of migration support from the framework, starting from "lightweight migration" that simple fills the new fields with nil, until "custom entity migration policies" that allows you to define callback functions that will do migration process of arbitrary complexity. See here.

In your case you could do the migration also manually, checking at every application start (or just once) whether the model is converted already, and if not, run a loop that fills the new entity based on the old ones.

Upvotes: 0

Related Questions