Search code examples
swift3realm

Can't create object with existing primary key value


I'm in my first steps of using Realm Mobile Database, and I would like to know if there is a way of handling the error caused by trying to add an object with the same primaryKey as one previously inserted, causing the following Can't create object with existing primary key value.

Here are my snippets:

class CategoryRLM: Object {
  dynamic var name: String = ""
  dynamic var desc: String = ""

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

static func addCategory(category: CategoryRLM) -> Bool {        
  let realm = try! Realm()
  do {
      try realm.write {
          realm.add(category)
      }

      return true
  }
  catch let error {
      print(error)
      return false
  }
}

Using the previous function:

if !CategoryRLM.addCategory(category: newCategory) {
  // There was an error while adding the object
}

The thing is that the error doesn't get handled by the do-catch.


Solution

  • Attempting to add an object with a primary key that already exists is classed as programmer error (that is, misuse of the API), and as such it is not possible to handle this error at runtime.

    In your case you should instead check if an object exists with that primary key prior to attempting to add the category to the Realm:

    static func addCategory(category: CategoryRLM) -> Bool {        
        let realm = try! Realm()
        if let existingCategory = realm.object(ofType: CategoryRLM.self, forPrimaryKey: category.name) {
            return false
        }
        try realm.write! {
            realm.add(category)
        }
        return true
    }