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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With