【问题标题】:Fatal Error :Can't open realm致命错误:无法打开领域
【发布时间】:2018-03-07 09:08:12
【问题描述】:

我正在开发 IOS。我在前端使用 realm 数据库。在我对领域模型和与之相关的所有文件进行一些更改之前,它工作正常。我只是在这些文件中添加了一个字段。

现在我在以下代码中收到错误“致命错误:无法打开领域”

fileprivate func getRealm() -> Realm {
    // get default configuration realm
    do {
        return try Realm()
    } catch {
        Swift.fatalError("Can't open realm")  //Fatal Error :Can't open realm
    }
}

谁能说出这个错误的可能原因。 提前致谢。

【问题讨论】:

    标签: ios swift realm realm-mobile-platform


    【解决方案1】:

    如果您对领域模型进行了更改,则需要增加架构版本,并且您可能需要或可能需要提供迁移块。 See官方文档了解详情。

    // Inside your [AppDelegate didFinishLaunchingWithOptions:]
    
    RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
    // Set the new schema version. This must be greater than the previously used
    // version (if you've never set a schema version before, the version is 0).
    config.schemaVersion = 1;
    
    // Set the block which will be called automatically when opening a Realm with a
    // schema version lower than the one set above
    config.migrationBlock = ^(RLMMigration *migration, uint64_t oldSchemaVersion) {
        // We haven’t migrated anything yet, so oldSchemaVersion == 0
        if (oldSchemaVersion < 1) {
            // Nothing to do!
            // Realm will automatically detect new properties and removed properties
            // And will update the schema on disk automatically
        }
    };
    
    // Tell Realm to use this new configuration object for the default Realm
    [RLMRealmConfiguration setDefaultConfiguration:config];
    
    // Now that we've told Realm how to handle the schema change, opening the file
    // will automatically perform the migration
    [RLMRealm defaultRealm];
    

    【讨论】:

    • 好的,谢谢!会检查
    【解决方案2】:

    上述问题是由于 Realm 数据库不一致造成的。我通过添加一个字段来更改模型的结构。因此,模型有 10 个字段,但我的应用程序中的领域数据库有 9 个字段,因为该应用程序是在更改之前构建的。

    我只是通过重新安装在手机中重新生成领域数据库的应用程序解决了这个问题,从而获得了一致的模型和数据库。

    如果您的应用尚未上线,上述解决方法可能会很好。但是,如果您的应用已经被其他用户使用,那么他们将不得不在更新时重新安装应用,这可能会导致用户体验不佳。

    理想情况下,您应该为新更改编写迁移块。 希望大家都清楚。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-22
      • 1970-01-01
      • 1970-01-01
      • 2013-07-23
      • 1970-01-01
      • 1970-01-01
      • 2014-04-21
      • 2011-04-02
      相关资源
      最近更新 更多