Avoid Adding Repeat Object to Realm

岁酱吖の 提交于 2019-12-04 10:49:41

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/28757153/avoid-adding-repeat-object-to-realm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!