我正在尝试使用记录的方法之一来迁移领域数据库并设置架构版本。我正在使用的代码的类型是:领域迁移,从何初始化
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()
- 如果我把这个在AppDelegate中的顶部上方如果我创建一个控制器@UIApplicationMain它初始化太早
- 文件,我打算在迁移后调用一个函数,并将其放在顶部,但仍然不起作用
如果我将它放在ViewController的类中,如下面的代码所示,错误Instanc Ë成员uiRealm不能在类型XYZViewController使用
import UIKit import RealmSwift class XYZViewController: UITableViewController,UIPickerViewDataSource,UIPickerViewDelegate { let uiRealm = try! Realm() var scenarios = uiRealm.objects(Scenario).filter("isActive = true ") }
所以我的问题是:是否有在哪里初始化的最佳做法,以及如何最好地迁移。
感谢您的支持,那么如何将以下内容转换为惰性初始化? scenario = uiRealm.objects(Scenario).filter(“isActive = true”)。如果我只是懒惰在前面我得到错误“使用未解析的标识符uiRealm” –
不用担心!嗯,有没有什么理由不使用Realm()代替uiRealm? – TiM
嗨,我通过声明var方案来解决这个问题:结果!在顶部,然后在每个函数内初始化领域。我又一次尝试做太多的全球食用,并将所有东西都转化为功能。 –