如何通过代码实现Core Data迁移?
How to implement Core Data migration by the 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(..)
一切都已迁移,映射工作正常,但关系丢失。
感谢您的帮助
自己找到了解决方案。
sourceEntityVersionHash
和 destinationEntityVersionHash
在 NSEntityMapping
上是必需的。
我目前正在通过代码试验迁移。只是为了了解幕后发生的事情。
属性没问题。但不是为了关系。
这是我的代码:
// 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(..)
一切都已迁移,映射工作正常,但关系丢失。
感谢您的帮助
自己找到了解决方案。
sourceEntityVersionHash
和 destinationEntityVersionHash
在 NSEntityMapping
上是必需的。