gpt4 book ai didi

ios - 具有非标准化数据的 Realm 迁移

转载 作者:行者123 更新时间:2023-11-30 13:43:38 25 4
gpt4 key购买 nike

假设您有一个 Realm 对象,例如

class Person: Object {
var dynamic firstName: String = ""
var dynamic lastName: String = ""
}

现在,我想升级数据库并将姓氏提取到一个像这样的新类中

class LastName: Object {
var dynamic sirName: String = ""

override public class func primaryKey() -> String {
return "sirName"
}
}

class Person: Object {
var dynamic firstName: String = ""
var dynamic lastName: LastName!
}

迁移会是什么样子?我尝试过简单的迁移,但这可能会导致多个 LastName 对象具有相同的 PrimaryKey。

最佳答案

在您的AppDelegatedidFinishLaunchingWithOptions中:

let configuration = Realm.Configuration(
schemaVersion: 1, //This must be larger than the previous schemaVersion
migrationBlock: { migration, oldSchemaVersion in
if oldSchemaVersion < 1 {
migration.enumerate(Person.className()) { oldObject, newObject in
let lastName = oldObject!["lastName"] as! String
let newValue: [String: String] = ["sirName": lastName]
let createdObject = migration.create(LastName.className(), value: newValue)
newObject!["lastName"] = createdObject
}
}
})

Realm.Configuration.defaultConfiguration = configuration // Set the new configuration as default

let realm = try! Realm() // Open the default realm to perform the migration

要补充的是,现在这也适用于 primaryKey ,模型如下所示:

class Person: Object {
dynamic var firstName: String = ""
dynamic var lastName: LastName!
}

class LastName: Object {
dynamic var sirName: String = ""

override static func primaryKey() -> String? {
return "sirName"
}
}

但是,如果 lastName 存在重复项,则此迁移将不起作用,因为 primaryKey 是每个对象的唯一标识符,因此您应该确保有永远不会重复,请为 primaryKey 使用另一个属性,或者在 LastName 对象中根本不使用 primaryKey

关于ios - 具有非标准化数据的 Realm 迁移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35254369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com