Jevon Çøö Jevon Çøö - 20 days ago 10
Swift Question

User made from Realm object has same Primary Key Realm

Im trying to use a real model to make a user profile, here is the model below:

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"
}

}


I'm adding objects to the default realm file via an IBAction button as shown here:

@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()
}


The issue is that the created user objects have the same "id"/Primary key:

Jane Vergo is 17 years old ID: A6A67E2D-C9A9-4D6B-815C-27BC22B3089B

Jake Lawson is 19 years old ID: A6A67E2D-C9A9-4D6B-815C-27BC22B3089B

Luke Cage is 20 years old ID: A6A67E2D-C9A9-4D6B-815C-27BC22B3089B

IS there anyway to make it so that each user has a different primary key/id?

Answer

Realm is an object database, so you need to create a new object every time:

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)

}
Comments