避免将重复对象添加到领域 [英] Avoid Adding Repeat Object to Realm

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

问题描述

我从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保证数据库中每个对象只有一个.

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

您仍然需要自行检查该对象是否已在数据库中.它将基于主键获取对象(通过property(A)或property(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 
  }

如果您使用主键并且不关心对象的值是否被更新,则可以使用

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.

希望这会有所帮助

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

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