领域迁移,在哪里初始化

时间:2016-10-02 17:15:09

标签: ios swift2 realm realm-migration

我尝试使用迁移领域数据库和设置架构版本的文档化方法之一。我正在使用的代码类型是:

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的类中,就像在下面的代码中一样,我得到错误实例成员uiRealm不能用于类型XYZViewController

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

所以我的问题是:是否有关于在何处初始化以及如何最佳迁移的最佳实践。

1 个答案:

答案 0 :(得分:1)

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

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

在代码有机会调用Realm()之前,尽快设置Configuration对象及迁移信息的最佳位置。因此,应用代表是一个很好的地方。

如果您已经预先配置了依赖于Realm()的类属性,那么将Realm()关键字添加到这些属性可能会有所帮助,因此它们的创建会延迟,直到您确实需要它们为止。< / p>