Reputation: 23
I am creating a project. I want if the userID
already exist, it doesn't add the user. But somehow my code isn't working properly.
This is my Realm Model Object (User.swift):
import Foundation
import RealmSwift
class User: Object {
@objc dynamic var userID = Int()
@objc dynamic var username = ""
@objc dynamic var full_name = ""
@objc dynamic var myBool = Bool()
override static func primaryKey() -> String? {
return "userID"
}
}
And this is the button to add users:
@IBAction func add(_ sender: Any) {
let myUser = User()
let JSON_userID = Int(arc4random_uniform(5)) // This is temporary. I am going to get code from JSON, but using random for testing purpose.
if (myUser.userID != JSON_userID) {
myUser.userID = JSON_userID
myUser.username = "myUsername"
myUser.full_name = "My Name"
let realm = try! Realm()
try! realm.write {
realm.add(myUser)
}
}
else {
print("Already exist")
}
}
Sometimes it runs the code, but most of the times it crashes with error:
libc++abi.dylib: terminating with uncaught exception of type NSException
.
Upvotes: 1
Views: 4843
Reputation: 1625
As you defined a primary key in your User
object, Realm can handle this automatically if you set the update
parameter to true
inside the write
closure.
let realm = try! Realm()
try! realm.write {
realm.add(myUser, update: true)
}
If the update
parameter is not set or false
, Realm will throw an exception when you try to add an object with an existing primary key.
This makes the if / else
condition useless. It can be removed.
If you need to know if the user already exists, you can request the Realm with the primary key value:
realm.object(ofType: User.self, forPrimaryKey: JSON_userID)
The result will be nil
if the user does not exist.
Upvotes: 3