spaceMonkey spaceMonkey - 1 year ago 385
iOS Question

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 =

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"

Answer Source

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 and let Realm pick one for you (not recommended)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download