【问题标题】:How to migrate old properties into a new object with Realm Swift如何使用 Realm Swift 将旧属性迁移到新对象中
【发布时间】:2016-11-20 11:39:38
【问题描述】:

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

这是我的对象的代码:

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)

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

【问题讨论】:

    标签: ios swift migration realm realm-migration


    【解决方案1】:

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

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

    【讨论】:

    • 是的,我正在做架构迁移。我试过你的答案,但我得到了这个错误:Value of type 'MigrationObject' (aka 'DynamicObject') has no member 'id'The object has an id field,所以它不应该显示错误。
    • 这实际上应该是other["id"]other["str"]。您收到该错误消息@Daniel 的原因是迁移块中的 Realm 对象不是您的类型化模型(在处理来自旧模式版本的对象时,这显然不起作用,其类型化模型不再存在)。
    • 我已经更新了答案以反映这一点。现在应该是正确的。
    猜你喜欢
    • 2016-03-20
    • 1970-01-01
    • 1970-01-01
    • 2020-05-31
    • 1970-01-01
    • 2017-05-27
    • 1970-01-01
    • 2016-02-06
    • 1970-01-01
    相关资源
    最近更新 更多