【发布时间】:2021-11-11 01:27:37
【问题描述】:
我正在尝试将具有List<String> 类型属性的对象迁移到List<ChildObject> 类型,其中ChildObject 是自定义EmbeddedObject。
示例
这就是我的意思:
import RealmSwift
final class ParentObject: Object {
// Previously, this property was of type `List<String>`.
@Persisted public var children: List<ChildObject>
}
final class ChildObject: EmbeddedObject {
@Persisted var name = ""
}
我正在使用此代码执行迁移,这会产生错误:
不能直接创建嵌入式对象
let configuration = Realm.Configuration(schemaVersion: 1) { migration, oldSchemaVersion in
if oldSchemaVersion < 1 {
migration.enumerateObjects(ofType: ParentObject.className()) { oldObject, newObject in
let childrenStrings = oldObject!["children"] as! List<DynamicObject>
let childrenObjects = newObject!["children"] as! List<MigrationObject>
// I'm trying to retain the previous values for `children` (of type `String`)
// where each value is used as the `name` property of a new `ChildObject`.
for string in childrenStrings {
childrenObjects.append(
// This line produces the error :(
migration.create(ChildObject.className(), value: [string])
)
}
}
}
}
let realm = try! Realm(configuration: configuration)
问题
如何在保留先前值的同时执行迁移?
【问题讨论】:
-
既然你只是用旧对象的值添加一个新对象,为什么不像你一样迭代childrenStrings并在那个循环中创建新对象
let c = ChildObject()分配值@ 987654329@并将其添加到对象中? -
嗨,杰。我遇到了几个类型不匹配的问题。在
c.name = string,我得到Cannot assign value of type 'DynamicObject'(到String)。正如 Rob 所说,我可以使用String(describing:)解决这个问题。但是,由于newObject!["children”]和ChildObject(c) 之间的类型不匹配,您说“将其添加到对象”时我有点迷失了。 -
实际上,这似乎运作良好:
newObject!["children"] = childrenStrings.map { /* create new child object and assign name */ } as [ChildObject]。感谢您指出这一点。 -
酷。我认为这可能有效。您提到的那个错误是因为字符串转换为
List<DynamicObject>。请参阅我对this question 的回答,以快速获取列表中的项目并将其转换为字符串。
标签: swift realm realm-migration realm-embedded-object