gpt4 book ai didi

ios - 如何使用 Realm Swift 将旧属性迁移到新对象中

转载 作者:行者123 更新时间:2023-11-28 16:03:08 25 4
gpt4 key购买 nike

以前,我只有一个对象具有我需要的所有值。我“重新组合”了它们并制作了单独的对象。我将具有新对象类型的属性添加到原始对象。如何将旧属性值分配给对象的属性?

这是我的对象的代码:

class MainObject: Object {
dynamic var id: Int = 0
// Schema 0
dynamic var otherId: Int = 0
dynamic var otherStr: String = ""

dynamic var anotherId: Int = 0
dynamic var anotherD: Double = 0.0
dynamic var anotherText: String = ""

// Schema 1
dynamic var otherObjectVar: OtherObject?
dynamic var anotherObjectVar: AnotherObject?
}

// Schema 1
class OtherObject: Object {
dynamic var id: Int = 0
dynamic var str: String = 0
}
class AnotherObject: Object {
dynamic var id: Int = 0
dynamic var d: Double = 0.0
dynamic var text: String = ""
}

(更改变量名称)

我尝试使用 convenience init(){} 但它没有用。我还尝试将一个对象实例分配给 newObject,但这也不起作用。这是为了更容易理解的代码:

let other = OtherObject()
other.id = 0
other.str = oldObject["otherStr"] as! string
newObject["otherObjectVar"] = other

如何将旧属性迁移到另一个对象的新属性中?

编辑:暂时,我解决了它

let obj = migration.create(MainObject.className())
migration.delete(obj)

但我认为这不是正确的解决方案。因此,如果有人对此有解决方案,我将不胜感激。

最佳答案

假设您在架构迁移期间执行此操作,您需要使用 migration.create 来创建新对象,而不是它们的 init。然后,您将按照以下行将它们设置在新对象上:

let other = migration.create(OtherObject.className())
other["id"] = 0
other["str"] = oldObject["otherStr"] as! String
newObject?["otherObjectVar"] = other

关于ios - 如何使用 Realm Swift 将旧属性迁移到新对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40703591/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com