在你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"
}
}
但这种迁移将无法正常工作如果由于primaryKey
是每个对象的唯一标识符而存在lastName
的重复项,则要么确保不会有重复项,请使用另一个属性作为primaryKey
或在LastName
对象中完全不使用primaryKey
。
这不起作用。它试图设置一个字典到newObject![“lastName”]属性 –
@NoName对不起,修复它,它现在应该如此! – xoudini
我相信这仍然可能会给出重复的姓氏对象具有相同的主键,从而给出错误 –