简体   繁体   中英

Update Realm primary key value swift

Im using Realm for my iOS app and for a table i have a primary key "name"

                let application  = Application()
                application.domain = app.domain
                application.name = app.name
                realm.add(application)

now when it try to update the name it throws an error

app?.name = newName

the error is

Primary key can't be changed after an object is inserted.

How do i solve this problem ?

this is how I declare the primary key

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

Once you insert an object with a primary key you cannot modify it:

From Realm Docs

primary key is added to a Realm, the primary key cannot be changed.

Which leave you with few options:

  • Remove and reinsert the object
  • Change the primary key to something that doesn't change, like id
  • Omit the Primary Key . If you don't define one, you don't have a primary key, which means you can have more than one object with the same value for this property and it won't be indexed by this property.

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