Namely
Namely

Reputation: 83

Proper way of avoiding duplicate object in Realm?

Lets say we have a Realm Object having a "title" property as a primary key. What is the proper way of checking existence of an object with the same key(title) and add accordingly? Without any error.

var personThatExists = Person.objectsWhere("id == %@", primaryKeyValueHere).firstObject()

  if personThatExists { 
    //don't add 
  } else { 
    //add our object to the DB 
  }

I have seen the above solution at https://stackoverflow.com/a/28771121/1919764

I believe there should be a better way.

Upvotes: 0

Views: 1578

Answers (1)

David Pasztor
David Pasztor

Reputation: 54716

Depending on whether you want to update the existing object with new data or do nothing if it exists already, you have two alternatives.

If you want to do nothing if it already exists, you can use Realm.object(ofType:,forPrimaryKey:).

let existingPerson = realm.object(ofType: Person.self, forPrimaryKey: primaryKey)

if let existingPerson = existingPerson {
    // Person already exists, act accordingly
} else {
    // Add person
}

If you want to update the object if it exists and add it if it doesn't, you can simply use realm.add(_:,update:).

do {
    try realm.write {
        realm.add(personObject,update:true)
    }
}

Upvotes: 2

Related Questions