简体   繁体   中英

Save User using Realm Object

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM