让我们说你有一个像
这样的领域对象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提取到像这样的新类
中$num = rand(0, count($family)-1);
$family[$num]
迁移会是什么样子?我尝试过一次简单的迁移,但这会导致多个LastName对象具有相同的primaryKey。
答案 0 :(得分:0)
在AppDelegate
didFinishLaunchingWithOptions
:
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
对象中使用primaryKey
的其他属性或根本不使用LastName
。