Aakash Dave
Aakash Dave

Reputation: 896

Updating realm object having primary key

I am trying to update a realm object with primary key. Now keep in mind I am not updating the primary key but only another field in there. Below is my my Object :

class UserData : Object {

@objc dynamic var name: String? = nil
@objc dynamic var bio: String? = nil
@objc dynamic var username: String? = nil
@objc dynamic var phone: String? = nil
@objc dynamic var uid : String? = nil
@objc dynamic var imageL: Data? = nil

override static func primaryKey() -> String {
    return "uid"
}

}

extension UserData {


func writeToRealm(){
    try? RealmService.uirealm.realm.write {
        RealmService.uirealm.realm.add(self, update: true)
    }
}

func DeleteFromRealm(object: Results<UserData>){
    try? RealmService.uirealm.realm.write {
        RealmService.uirealm.realm.delete(object)
    }
}

}

This is How I am instantiating the realm Service in my program :

class RealmService {

static let uirealm = RealmService()

private var _initRS = try! Realm()

var realm: Realm! {
    return _initRS
}
}

I am trying to update the "bio" property of the object but am Contiuiosly given an

exception for "unable to update primary key"

Now, I really don't understand why I am being thrown this error even though I am not updating the primary key in the object.

Extra Notes:

I am updating the realm object on every observable change of the firebase instance. So this is the area where i am having the problem. Because there is going to be a only one write realm instance everytime a change occurs.

Code for the same :

FBDataservice.ds.REF_USERS.child(uuid).observe(.value, with: { (snapshot) in
        if snapshot.hasChild("credentials") {
            if let snap = snapshot.value as? Dictionary<String, Any> {
                if let cred = snap["credentials"] as? Dictionary<String, Any> {

                    let u = User(userid: uuid, userData: cred)
                    self.usercache.uid = uuid
                    self.usercache.bio = u.aboutme
                    self.usercache.writeToRealm()
                }
            }
        }
//            RealmService.uirealm.realm.refresh() ------> No sure about this
    })
}

Upvotes: 1

Views: 572

Answers (1)

phapli
phapli

Reputation: 647

I think problem is in this line

self.usercache.uid = uuid

Because self.usercache is already a Realm object, so when you update it's uid => it throw exception.

Instead of re-use self.usercache, try create a new UserData object

Upvotes: 1

Related Questions