【问题标题】:Realm migration, where to initialise领域迁移,在哪里初始化
【发布时间】:2016-10-02 17:15:08
【问题描述】:

我正在尝试使用一种记录在案的方法来迁移领域数据库并设置架构版本。我使用的代码是:

let config = Realm.Configuration(
    // 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).
    schemaVersion: 1,

    // Set the block which will be called automatically when opening a Realm with
    // a schema version lower than the one set above
    migrationBlock: { migration, oldSchemaVersion in
        // 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
Realm.Configuration.defaultConfiguration = config

这似乎是非常标准的代码,并且看起来被其他人使用。但是,似乎让我感到困惑的是我正在初始化 Realm 实例,这导致架构设置无法设置或持续存在。

我正在努力的是在哪里设置以下代码:

let uiRealm = try! Realm()
  • 如果我把它放在 @UIApplicationMain 上方的 AppDelegate 的顶部,它初始化得太早了
  • 如果我创建了一个控制器文件,我打算在迁移后调用一个函数,并将初始化程序放在它仍然不起作用的顶部
  • 如果我将它放在 ViewController 的类中,如下面的代码所示,我会收到错误 Instance member uiRealm cannot be used on type XYZViewController

    import UIKit
    import RealmSwift
    
    class XYZViewController: UITableViewController,UIPickerViewDataSource,UIPickerViewDelegate {
    
        let uiRealm = try! Realm()
        var scenarios = uiRealm.objects(Scenario).filter("isActive = true ")
    
    }
    

所以我的问题是:有没有关于在哪里初始化以及如何最好地迁移的最佳实践。

【问题讨论】:

    标签: ios swift2 realm realm-migration


    【解决方案1】:

    在代码的任何其他部分调用 Realm() 之前,您需要确保已将 Configuration 对象设置为 Realm 的默认配置。

    最好的做法是不要保留对Realm() 的任何引用,除非您有充分的理由。每次调用 Realm() 时,它都会返回一个之前缓存的对象实例,因此通过创建对实例的引用并在应用的生命周期中挂起该实例并不会带来性能优势。

    使用迁移信息设置Configuration 对象的最佳位置是在代码有机会调用Realm() 之前尽快。所以应用程序委托是一个很好的地方。

    如果您已经预配置了依赖于 Realm() 的类属性,那么在这些属性前面添加 lazy 关键字可能会有所帮助,这样它们的创建就会延迟到您真正需要它们为止。

    【讨论】:

    • 谢谢您,那么如何将以下内容转换为惰性初始化?场景 = uiRealm.objects(Scenario).filter("isActive = true")。如果我只是把惰性放在前面,我会收到错误“使用未解析的标识符 uiRealm”
    • 别担心!嗯,有什么理由不能只使用Realm() 而不是 uiRealm?
    • 嗨,我通过声明 var 场景解决了这个问题:Results!在顶部,然后在每个函数中初始化领域。再次,我试图做太多的全球食品,并将所有东西都转移到功能中。
    • 此外。添加以下代码为我们提供了初始化程序lazy var uiRealm:Realm = { return try!领域() }()
    猜你喜欢
    • 2017-02-20
    • 2014-04-27
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    • 2023-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多