【问题标题】:RealmSwift: Realm at path already opened with different schema versionRealmSwift:路径中的领域已经使用不同的模式版本打开
【发布时间】:2016-05-13 09:47:52
【问题描述】:

我最近创建了一个新分支并尝试重构我的大部分代码,以使 RealmCoreData 更具优势。但到目前为止,我还没有让我的代码运行的运气。

首先,shared_realm.cpp 中抛出异常。抛出错误的代码行是:

if (realm->config().schema_version != config.schema_version && config.schema_version != ObjectStore::NotVersioned) {
   throw MismatchedConfigException("Realm at path already opened with different schema version.");
}

如果我跳过这个异常,它会捕获下面的第二行代码:

class func getAllCategories() -> Results<Category> {
    let realm = try! Realm()
    let categories = realm.objects(Category)

    return categories
}

并抛出此错误消息:

致命错误:“试试!”表达式意外引发错误:错误 Domain=io.realm Code=1 "路径中的领域已经以不同的方式打开 架构版本。” UserInfo={NSLocalizedDescription=Realm at path 已使用不同的架构版本打开。错误代码=1}

我对 Realm 完全陌生,因此感谢您提供任何帮助。我对文档的理解是 Realm() 是访问默认数据库的正确方法,目前这对我来说很好。起初我以为可能需要传递一个 Realm,但我从网上的例子中看到,情况似乎并非如此。

我已经清理、更改了模拟器,甚至更新了 Xcode。我还尝试将这行代码注释回:

// FIXME - enable schema comparison
/*if (realm->config().schema != config.schema) {
  throw MismatchedConfigException("Realm at path already opened with different schema");
}*/

无济于事。感觉很迷茫,所以任何方向都值得赞赏。

【问题讨论】:

  • 您是否在任何地方使用 Realm Configuration 对象来设置 Realm 的默认配置?如果是这样,你能把它贴在这里吗?此外,如果您对 Category 对象进行大量开发更改,您是否尝试过删除磁盘上的 Realm 文件并让 Realm 创建一个新文件?

标签: ios xcode swift realm


【解决方案1】:

路径的架构版本在打开后无法更改,因此您需要在使用 setSchemaVersion 调用路径之前更改架构。

setSchemaVersion(1, realmPath: Realm.defaultPath) { (migration, oldSchemaVersion) -> Void in
    if oldSchemaVersion < 1 {
        migration.enumerate(Category.className(), { (oldObject, newObject) -> Void in
            let constant = oldObject!["constant"] as! String
            newObject!["constant"] = constant
        })
    }
}

【讨论】:

    【解决方案2】:

    您可能会遇到这个问题,因为您在构建应用程序一次后更改了架构(只是猜测,您可以通过删除应用程序并重新构建它来确认这一点,这也会清除现有的领域数据库。)

    如果这确实是问题,您应该调查一下 https://realm.io/docs/swift/latest/#migrations 其中概述了解决此问题的推荐方法。

    【讨论】:

      【解决方案3】:

      对我来说,问题是我添加了一个新字段作为这样的字符串:

              schema.get("RealmCompany").addField("ctype", String.class);
      

      当我在模型类中将它声明为整数时。

      我不得不这样做:

              if (oldVersion == 7) {
                  Log.i(TAG, "migrate: " + 7);
                  schema.get("RealmCompany").removeField("ctype");
                  schema.get("RealmCompany").addField("ctype", Integer.class);
      
              }
      

      【讨论】:

        猜你喜欢
        • 2018-06-14
        • 2018-07-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-17
        • 2012-05-03
        • 2017-05-30
        • 1970-01-01
        相关资源
        最近更新 更多