避免向 Realm 添加重复对象 [英] Avoid Adding Repeat Object to Realm

查看:37
本文介绍了避免向 Realm 添加重复对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从 Parse.com 查询数据并将它们保存在本地 Realm 数据库(iOS/swift)中.每个对象都有一个独特的属性(A),但也有一个可能相同的属性(B).避免将具有相同属性 B 的对象添加到领域数据库的最有效方法是什么?提前致谢.

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.

推荐答案

你可以在一个对象上设置一个主键,这样 Realm 保证每个对象在 DB 中只有一个.

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"
    }
}

您仍然需要自己检查该对象是否已经在数据库中.它将根据主键获取对象(通过属性(A)或属性(B)查找对象).然后对象存在就不要添加,不存在就添加到数据库中.

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.

像这样:

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

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

如果你使用主键并且你不关心对象的值被更新,你可以使用 createOrUpdate 方法.如果一个对象不存在,Realm 将创建一个新对象,否则它将使用您传入的对象中的值更新存在的对象.

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.

希望能帮到你

这篇关于避免向 Realm 添加重复对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆