由于未命中 RLMRealm.setSchemaVersion 块,无法迁移到具有更新属性的新模式

Unable to migrate to new schema with updated properties due to RLMRealm.setSchemaVersion block not being hit

我已将以下两个属性添加到我的 RLMObject 中,但我似乎无法按照文档更新它。这是我的属性:

dynamic var firstName = ""
dynamic var lastName = ""

这是我的迁移逻辑(在我的 AppDelegate 中,包含在 didFinishLaunchingWithOptions 中,据我所知,应该将这些属性添加到领域文件中:

RLMRealm.setSchemaVersion(1, forRealmAtPath: RLMRealm.defaultRealmPath(), withMigrationBlock: { migration, oldSchemaVersion in

        if oldSchemaVersion < 1 {

        }

})

以及抛出的异常:

'RLMException', reason: 'Migration is required for object type 'FilteredAccount' due to the following errors:
- Property 'firstName' has been added to latest object model.
- Property 'lastName' has been added to latest object model.'

当我在这个块中放置断点时,它们没有命中。我的应用程序在 AppDelegate 的顶部崩溃并且从不执​​行迁移代码。当我删除这些属性时,应用程序打开得很好。如果我删除整个领域,它也是固定的,但显然每次更改我的数据模型时这样做效率不高。

任何帮助将不胜感激。谢谢!

您似乎在调用 RLMRealm.setSchemaVersion 之前打开领域,这肯定会导致该异常。

如果您分享了您的 didFinishLaunchingWithOptions 方法的全部内容(假设这是您设置领域的地方),我们可以验证这一点。

编辑

由于您已经向 RLMObject 子类添加了两个属性,而 Realm 尚不支持可选的字符串属性,因此您需要为 firstNamelastName 分配一个值到迁移块内的所有现有 FilteredAccount 对象,如下所示:

RLMRealm.setSchemaVersion(1, forRealmAtPath: RLMRealm.defaultRealmPath(), withMigrationBlock: { migration, oldSchemaVersion in

        if oldSchemaVersion < 1 {
              migration.enumerateObjects(FilteredAccount.className()) { oldObject, newObject in
                    newObject["firstName"] = ""
                    newObject["lastName"] = ""
              }
        }

})