Roman Romanenko
Roman Romanenko

Reputation: 766

Update model Realm Swift

I'm a new in Realm and ask you to help me. I created the model:

class UserModel: Object {

    dynamic var email = ""
    dynamic var facebook_id = ""
    dynamic var google_id = ""
    dynamic var id = 0
    dynamic var name = ""
    dynamic var photo = ""
    dynamic var someinfo = ""
    dynamic var twitter_id = "" 

}

When I login to app, I can see my info on UserProfileController. Also I have a EditProfileController where I can change some info about myself. So when I successfully change it, I want to update my Realm model, and try to do this:

    let realm = try! Realm()

    try! realm.write {
        realm.create(UserModel.self, value: ["name": self.editEmail.text!, "email": self.editEmail.text!], update: true)
    }

But unfortunately I see this message:

''UserModel' does not have a primary key and can not be updated'

What if I want to update a few property at the same time? Can I do this with primaryKey? Or... How it possible to update Realm model without primaryKey?

Upvotes: 6

Views: 8643

Answers (2)

Tj3n
Tj3n

Reputation: 9943

The problem lie in this update: true, it's used to automatically replace object that have the same primary key in your realm, if your object don't have primary key, set update to false then it will work and always create new object

Upvotes: 7

wint
wint

Reputation: 1286

You need to set a primary key for your UserModel.

https://realm.io/docs/swift/latest/#primary-keys

Upvotes: 0

Related Questions