iosswiftcore-datacore-data-migration

How to implement Core Data migration by the code?


I currently experiment migration by the code. Just for understand what happened under the hood.

It's OK for attributes. But not for relationships.

Here is my code:


// Mapping model
let model = NSMappingModel()

// Migration code for list (with items relationship One-To-Many)
let list = NSEntityMapping()

// ...


// Migration code for item (with list relationship One-To-One)
let item = NSEntityMapping()

// Migration of attributes: OK
item.attributeMappings = [ ]

// Migration of relationships: KO
let property = NSPropertyMapping()
property.name = "list"
property.valueExpression = NSExpression(format: """
FUNCTION($manager, "destinationInstancesForEntityMappingNamed:sourceInstances:" , "ItemV1ToItemV2", $source.list)
""")
item.relationshipMappings = [property]

// ...

return model // Used by NSMigrationManager.migrateStore(..)

Everything is migrated, mapping works fine, but relationships are lost.

Thank you for your help 😁


Solution

  • Found the solution myself.

    sourceEntityVersionHash and destinationEntityVersionHash are required on NSEntityMapping.