I'm trying to perform a Realm migration with the following code:
let version = try! schemaVersionAtURL(Realm.Configuration.defaultConfiguration.fileURL!)
let config = Realm.Configuration(
schemaVersion: version + 1,
migrationBlock: { migration, oldSchemaVersion in
if oldSchemaVersion < 1 {
migration.enumerateObjects(ofType: MyObject.className()) { oldObject, newObject in
// Here I transfer existing data to new properties
}
}
})
Realm.Configuration.defaultConfiguration = config
let _ = try! Realm()
The migration seems to work fine, but the next time the app is relaunched, both the current and old schema versions are 0, despite having been set to 1 by the migration that occurred during the first launch.
But the migration is done, so the if
condition is true, and the app crashes with a Realm exception caused by trying to perform the migration again.
Can anyone help me understand what I'm missing? If the configuration is setting the schema version to 1 during the migration, why is it 0 the next time the app is relaunched?
Turns out the issue was actually calling Realm before the migration was performed. I'd forgotten a bit of code I had running in willFinishingLaunchingWithOptions
that called it.
Lesson Learned: Only the very first call to Realm performs the migration.