Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Realm - Delete objects from realm in migration block

Tags:

swift

realm

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 ?

like image 540
nth Avatar asked Nov 02 '16 14:11

nth


2 Answers

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)
        ...
like image 84
kishikawa katsumi Avatar answered Jan 02 '23 07:01

kishikawa katsumi


You can tell Realm to delete when migration needed.

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


    },
    deleteRealmIfMigrationNeeded: true
)
like image 21
wint Avatar answered Jan 02 '23 09:01

wint