Search code examples
swiftrealm

How can I add or update a Realm object in Swift?


I have a Realm object that may or may not have been added to Realm yet, and I want to update a property (while adding it if it hasn't been added yet).

Here's how I'm doing this right now:

try! realm.write {
  if cat.realm == nil {
    realm.add(cat)
  }
  cat.name = "Photon"
}

Is checking if the object has a realm attached to it the correct way to determine if it's been added or not?


Solution

  • Yes. Checking Object.realm == nil is the best way to see if an object has already been inserted into a Realm or not yet. :)