9

I need to delete objects from a realm during a migration.

I have an AccountManager which contains :

func logOut() {
    let realm = try! Realm()
    try! realm.write {
        realm.delete(realm.objects(Account.self))
        realm.delete(realm.objects(Address.self))
        ... // Other deletions
    }
}

But whenever I use the logOut() function in a migration block it just fails.

    let config = Realm.Configuration(
        schemaVersion: 11,
        migrationBlock: { migration, oldSchemaVersion in
            if (oldSchemaVersion < 11) {
                // Delete objects from realm
                AccountManager().logOut() // DOESN'T WORK
            }
    })

    Realm.Configuration.defaultConfiguration = config

I absolutely need users to relog after this update - Is there any way I could perform these deletions in a migration block ?

2 Answers 2

18

You can use Migration.deleteData(forType typeName: String) instead Realm.delete(_:) as follows.

Realm.Configuration(schemaVersion: 11, migrationBlock: { migration, oldSchemaVersion in
    if oldSchemaVersion < 11
        migration.deleteData(forType: Account.className)
        migration.deleteData(forType: Address.className)
        ...
Sign up to request clarification or add additional context in comments.

1 Comment

Hi , please check my question about realm migration , stackoverflow.com/questions/59855380/…
14

You can tell Realm to delete when migration needed.

Realm.Configuration.defaultConfiguration = Realm.Configuration(
    schemaVersion: 10,
    migrationBlock: { migration, oldSchemaVersion in


    },
    deleteRealmIfMigrationNeeded: true
)

3 Comments

Is there any way I could specify this realm deletion only has to be applied when migrating from version 10 to 11 ?
I never try that, I guess you have to write your own migration code. Check out this answer stackoverflow.com/a/40467810/2003085
for deleting realm only when migrating from certain versions, check out github.com/realm/realm-js/issues/502#issuecomment-228058951

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.