This is the object I created with primary key username and the error when I try to run the add object code.
class Login_item: Object {
dynamic var username = String()
dynamic var password = String()
override static func primaryKey() -> String? {
return "username"
}
}
This is the code that add new object and update object.
func save_login_info() {
let new_login_entry = Login_item()
new_login_entry.username = Username.text!
new_login_entry.password = Password.text!
let realm = try! Realm()
try! realm.write {
realm.add(new_login_entry)
print("Login info save as: \(Realm.Configuration.defaultConfiguration.fileURL!)")
}
try! realm.write {
realm.add(new_login_entry, update: true)
}
}
Error I got when execute the code.
致命错误:'试试!'表达式意外地引发了错误:Error Domain = io.realm Code = 10“由于以下错误,需要迁移: - 属性'username'已成为主键 . ” UserInfo = {NSLocalizedDescription =由于以下错误而需要迁移: - 属性'用户名'已成为主键 . ,错误代码= 10}:file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang -703.0.18.8 / src / swift / stdlib / public / core / ErrorType.swift,第54行
1 回答
是的,你需要在更改模型时添加迁移指令,这就是错误消息描述的内容 .
代码中的1代表当前版本,每次对代码进行任何更改时,都需要增加版本号并对所需的数据进行任何更改 .
你可以阅读更多关于它的信息here