Migration does not working: I hope to know the execution condition


Hello, I made a migration function as below, and call it in AppDelegate.

class func migrationDB() {
    var migrated: Bool = false
    do {
        let schemaVersion = try schemaVersionAtURL(Realm.Configuration(encryptionKey: ENCRYPTION_KEY).fileURL!, encryptionKey: ENCRYPTION_KEY)
        print("schemaVersion", schemaVersion)
    } catch {
        print("Error in reading schemaVersion", error)
    let migrationBlock: MigrationBlock = { migration, oldSchemaVersion in
        print("migration, oldSchemaVersion", migration, oldSchemaVersion)
        migration.enumerateObjects(ofType: Outgo.className(), { oldObject, newObject in
            if (oldSchemaVersion < 1) {
                newObject?["newColumn"] = 0
                migrated = true
        print("Migration complete.")
    Realm.Configuration.defaultConfiguration = Realm.Configuration(encryptionKey: ENCRYPTION_KEY, schemaVersion: LOCAL_DB_VERSION, migrationBlock: migrationBlock)
    print("migrated", migrated)


schemaVersion 0
migrated false

The schemaVersion logged in the do~catch block is 0.
And the value of constant LOCAL_DB_VERSION is 1 now.
But it seems like the migrationBlock is not triggered.
I hope to know why, and the execution condition exactly.

Thank you.


Can you try to print the new schemaVersion after the print(“migrated”, migrated) too?


Sure. it’s ‘0’, too.

schemaVersion 0
migrated false
schemaVersion 0


That that why your migration block is not called. The new realm version is the same as the old one.


Its probably true, but do you open the realm? The new settings will apply only when you open a new Realm.


Thank you for your reply.

But of course I tried to open the realm right after the migration method…


How and where can I set the newer version? Is this here?

Realm.Configuration(encryptionKey: ENCRYPTION_KEY, schemaVersion: LOCAL_DB_VERSION, migrationBlock: migrationBlock)

and old schemaVersion is 0 as the log.
I can’t understand how it works.


Thank you so so much. I got it.
I found the reason! I forgot to LOAD REALM WITH NEW CONFIGURATION!


Nice catch.
Glad that you finally found out.