我尝试使用真实模型制作用户个人资料,以下是以下模型:
class UserProfile: Object {
dynamic var id = UUID().uuidString
dynamic var name:String = ""
dynamic var age = ""
dynamic var email = ""
dynamic var userName = ""
dynamic var passWord = ""
override static func primaryKey() -> String? {
return "id"
}
}
我通过IBAction按钮将对象添加到默认域文件中,如下所示:
@IBAction func signUpButton(_ sender: UIButton) {
try! realm.write {
user.userName = userNameTextField.text!
user.passWord = passWordTextField.text!
user.email = emailTextField.text!
user.name = fullNameTextField.text!
user.age = ageTextField.text!
user.id = UUID().uuidString
realm.add(user)
}
userQuery()
}
问题是创建的用户对象具有相同的" id" /主键:
Jane Vergo今年17岁,身份证号码:A6A67E2D-C9A9-4D6B-815C-27BC22B3089B
杰克劳森19岁身份证号:A6A67E2D-C9A9-4D6B-815C-27BC22B3089B
Luke Cage年满20岁ID:A6A67E2D-C9A9-4D6B-815C-27BC22B3089B
无论如何要做到这一点,以便每个用户都有不同的主键/ ID?
答案 0 :(得分:1)
Realm是一个对象数据库,因此您每次都需要创建一个新对象:
try! realm.write {
user = User() // Create a new user instance
user.userName = userNameTextField.text!
user.passWord = passWordTextField.text!
user.email = emailTextField.text!
user.name = fullNameTextField.text!
user.age = ageTextField.text!
user.id = UUID().uuidString
realm.add(user)
}