Search code examples
iosobjective-ccore-datacore-data-migration

Core Data rename attribute "deleted"


I'm migrating a Data Model using a Mapping Model.

An entity has an attribute named deleted that is not migrating because Core Data takes the deleted property of the NSManagedObject instead of mine.

How can I force the Mapping Model to use my attribute?

Is there anything I can use in the Value Expression? This is what I use now:

enter image description here

Thank you.


Solution

  • I've found the solution:

    I implemented a custom MigrationPolicy as follow:

    - (BOOL)createDestinationInstancesForSourceInstance:(NSManagedObject *)sourceInstance
                                      entityMapping:(NSEntityMapping *)mapping
                                            manager:(NSMigrationManager *)manager
                                              error:(NSError *__autoreleasing *)error
    {
        NSManagedObject *newObject = [NSEntityDescription insertNewObjectForEntityForName:[mapping destinationEntityName] inManagedObjectContext:[manager destinationContext]];
    
        // Add the old 'deleted' attribute to a renamed attribute
        [newObject setValue:[NSNumber numberWithBool:[((OldEntityModel *)sourceInstance) deleted]] forKey:@"newDeletedAttribute"];
    
        // Add all the other attributes
        [newObject setValue:[sourceInstance valueForKey:@"field1"] forKey:@"field1"];
        [newObject setValue:[sourceInstance valueForKey:@"field2"] forKey:@"field2"];
    
        // Add the relationships
        NSSet *relationshipAttribute = [[NSSet alloc] initWithArray:[manager destinationInstancesForEntityMappingNamed:@"OtherEntityToOtherEntity" sourceInstances:@[[sourceInstance valueForKey:@"relationshipAttribute"]]]];
        [newObject relationshipAttribute forKey:@"relationshipAttribute"];
    
        [manager associateSourceInstance:sourceInstance withDestinationInstance:newObject forEntityMapping:mapping];
    
        return YES;
    }
    

    Casting the sourceEntity to the old model version permits to access the deleted attributed that was unaccessible in lightweight migrations or mapping models.