Realm Property的数据类型迁移

Kei*_*eoh 3 objective-c realm

我正在尝试为我的Model文件中的某个属性执行数据类型的迁移.

我发现的来源主要是指导如果列的名称更改或将列合并为一个如何迁移.

这是我编译应用程序时收到的错误消息.

由于未捕获的异常'RLMException'而终止应用程序,原因:'由于以下错误需要迁移: - 'has_completed_profile'属性的属性类型不匹配.旧类型'bool',新类型'int'

我使用的是最新版本0.99.0

kis*_*umi 6

首先,在更改模型类的定义时,应增加模式版本.

然后,如果使用新数据模式保留旧数据,则应将旧数据迁移到迁移块中的新模式.

例如:

// Schema version 0
class TestObject: Object {
    dynamic var name = "Test"
    dynamic var has_completed_profile = false
}

// Schema version 1
class TestObject: Object {
    dynamic var name = "Test"
    dynamic var has_completed_profile = 5
}
Run Code Online (Sandbox Code Playgroud)

如果您将列时间更改BoolInt,并且您希望保留旧数据,则应编写迁移块,如下所示:

let config = Realm.Configuration(schemaVersion: 1, migrationBlock: { (migration, oldSchemaVersion) in
    if oldSchemaVersion < 1 {
        migration.enumerate(TestObject.className(), { (oldObject, newObject) in
            // Migrate old column to new column
            // If there is no compatibility between two types
            // (e.g. String to Int)
            // you should also write converting the value.
            newObject!["has_completed_profile"] = oldObject!["has_completed_profile"]
        })
    }
})
let realm = try! Realm(configuration: config)
Run Code Online (Sandbox Code Playgroud)