Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid Adding Repeat Object to Realm

I query down the data from Parse.com and save them in the local Realm database (iOS/swift). Each object has a unique property(A) but also a might-be-same property(B). What is the most efficient way to avoid adding objects with same property B into the realm database? Thanks in advance.

like image 806
Zhehao Victor Zhou Avatar asked Feb 27 '15 03:02

Zhehao Victor Zhou


1 Answers

You can set a primary key on an object so that Realm guarantees that there is only one of each object in the DB.

class Person: RLMObject {
    dynamic var id = 0
    dynamic var name = ""

    override class func primaryKey() -> String {
        return "id"
    }
}

You will still need to do a check yourself whether that object is in the DB already or not. It would fetch the object based on the primary key (either looking for objects via property(A) or property(B)). Then if the object exists, don't add, if it doesn't exist, add it to the DB.

Something like this:

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

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

If you use primary keys and you don't care about the object's values being updated, you can use the createOrUpdate method. Realm will create a new object if one doesn't exist, otherwise it will update the one that exists with the values from the object you pass in.

Hope this helps

like image 154
yoshyosh Avatar answered Sep 29 '22 17:09

yoshyosh