I've added a value to a realm object (I've added dynamic var inspectorName = "" to the WeekReport object), and I'm trying to migrate the realm database to contain that value. I'm trying to call the migration block in func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil)
like this:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
print("HERE")
Realm.Configuration.defaultConfiguration = Realm.Configuration(
schemaVersion: 1,
migrationBlock: { migration, oldSchemaVersion in
if (oldSchemaVersion < 1) {
migration.enumerateObjects(ofType: WeekReport.className()) { oldObject, newObject in
newObject!["inspectorName"] = ""
}
}
})
return true
}
But it seems that didFinishLaunchingWithOptions
isn't called before my error happens.
In multiple view controller i have let realm = try! Realm()
. Here Xcode breaks when I run the app:
"Migration is required due to the following errors: - Property 'WeekReport.inspectorName' has been added." UserInfo={NSLocalizedDescription=Migration is required due to the following errors: - Property 'WeekReport.inspectorName' has been added., Error Code=10}: file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-800.0.63/src/swift/
How come the migration blick isn't called? "HERE" is never printed...
Should I define realm in a different way in my view controllers?
If you write let realm = try! Realm()
in a view controller as an instance variable, it will be called before application: didFinishLaunchingWithOptions
from Storyboard. To resolve this, you can use lazy var realm = try! Realm()
instead. lazy
defers creating an instance variable until the variable is accessed.