在你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
我相信這仍然可能會給出重複的姓氏對象具有相同的主鍵,從而給出錯誤 –