Avoid Adding Repeat Object to Realm

前端 未结 1 1426
悲哀的现实
悲哀的现实 2021-02-08 03:04

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 th

相关标签:
1条回答
  • 2021-02-08 03:41

    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

    0 讨论(0)
提交回复
热议问题