I'm trying to work with one of the documented methods of migrating a realm database and setting the schema version. The kind of code I am using is:
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
This seems to be pretty standard code, and looks to be used by others. However, what seems to be tripping me up is where I am initialising the Realm instance which is causing the schema setting not to set or persist.
what I am struggling with is where to set the following code:
let uiRealm = try! Realm()
- If I put this at the top of AppDelegate above @UIApplicationMain it initialises too early
- If I create a controller file, that I intend to call a function within after the migration, and put the initialiser at the top of that it still doesn't work
If I put it within the class of a ViewController as in the code below I get the error 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 ") }
So my question is: are there any best practices on where to initialise, and how best to migrate.