领域 - 在迁移块中从领域中删除对象

时间:2016-11-02 14:07:44

标签: swift realm

我需要在迁移过程中从域中删除对象。

我有一个AccountManager,其中包含:

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

但每当我在迁移块中使用logOut()函数时,它就会失败。

    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

我绝对需要用户在此更新后重新登录 - 我是否可以在迁移块中执行这些删除?

2 个答案:

答案 0 :(得分:8)

您可以告诉Realm在需要迁移时删除。

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


    },
    deleteRealmIfMigrationNeeded: true
)

答案 1 :(得分:8)

您可以使用Migration.deleteData(forType typeName: String)代替Realm.delete(_:),如下所示。

Realm.Configuration(schemaVersion: 11, migrationBlock: { migration, oldSchemaVersion in
    if oldSchemaVersion < 11
        migration.deleteData(forType: Account.className)
        migration.deleteData(forType: Address.className)
        ...