领域模型迁移策略

Realm model migration strategy

我 运行 在使用 Realm 迁移块和迁移领域的策略时遇到问题。

给定一个具有多个属性的对象 MyObject:

给定以下迁移块:

    private class func getMigrationBlock(realmPath: String) -> RLMMigrationBlock {
    return { migration, oldSchemaVersion in
        if (oldSchemaVersion == RLMNotVersioned) {
            NSLog("No database found when migrating.")
            return
        } else {
            NSLog("Migrating \(realmPath) from version \(oldSchemaVersion) to \(RealmMigrationHelper.CURRENT_DATABASE_VERSION)")
        }

        NSLog("Upgrading MyObject from version %d to %d", oldSchemaVersion, CURRENT_DATABASE_VERSION)
        if (oldSchemaVersion < 2) {
            migration.enumerateObjects(MyObject.className(), block: {
                oldObject, newObject in
                newObject["myPropertyMk2"] = oldObject["myProperty"]
            })
        } 
        if (oldSchemaVersion < 3) {
            migration.enumerateObjects(MyObject.className(), block: {
                oldObject, newObject in
                newObject["myPropertyMk3"] = oldObject["myPropertyMk2"]
            })
        } 
        NSLog("Migration complete.")
    }
}

当我是数据库的第 2 版时,它工作得很好(显然没有 oldSchemaVersion < 3 块),但是当我引入第 3 版时,我开始遇到问题,因为它不识别 newObject["myPropertyMk2"]oldSchemaVersion < 2 块中。如果我将它更改为 newObject["myPropertyMk3"] 它工作得很好。

从阅读 RLMMigration 代码来看,这非常有意义,因为我们使用旧方案和新方案,但根据 realm.io 上的文档,我认为它没有意义。那我本以为它会少一些方案。

我有一个想法,就是通过简单地使用字典来减少块内迁移的方案,然后最终将这个字典应用到 newObject

对于处理这个问题的领域的迁移策略有什么想法吗?它在 realms 网站上有提及,但只是非常简短。

谢谢:)

感谢您提出问题并报告您的问题。

From reading the RLMMigration code this makes perfectly good sense as we work with the old schme and the new scheme, but based on the documentation on realm.io I do not think it makes sense. Then I would have expected it to be scheme less.

正如您从 RLMMigration 中的代码正确识别的那样,迁移不是无方案的。您提供的迁移闭包应该处理从过去任何版本到当前版本的迁移。如果您的用户在此期间没有更新您的应用程序并因此跳过了一个版本,那么 Realm 就不可能知道您的中间模式版本,因为模式会在运行时反映出来。您通常可以故意破坏与现有旧版本的向后兼容性,但您需要注意将配置重置为定义的状态。

您肯定是对的,可以更好地记录这一点。我已经为此创建了一张内部票。

I have an idea about making a scheme less migration within the block by simply using a dictionary and then finally apply this dictionary to the newObject.

Are there any thoughts on the migration strategy of realms that deals with this? It is mentioned on realms website, but only very briefly.

根据您的方案和您拥有的数据量,您可以通过字典在内存中按对象重新组织它,然后按照您的描述将其应用于 newObject。当前的 API 做出相对较少的假设并允许这样的方法。但它不会以对每个人都有好处的方式工作,例如。如果您有大量相关对象列表。