copyToRealm 或更新和删除

copyToRealmOrUpdate and Delete

我需要在我的应用程序中同步数据。我向服务器发出请求,绑定并使用 copyToRealmOrUpdate(Iterable<E> objects) 将此数据添加或更新到数据库中。

但是我的文件可能会失效,我需要一些东西来删除请求中 return 数据中没有的所有内容。我不想截断或手动删除来执行此操作,因为性能很重要。

想法 1

@beeender

你觉得用table的PRIMARY_KEY删除我不想要(或不需要)的数据怎么样?

看起来像:

在这种情况下,也许 In memory Realm 对您来说是个不错的选择。您可以找到相关文档 here .

通过使用内存领域:

  • 当您启动一个新的应用程序进程时,数据库将为空
  • 关闭Realm的所有实例后,数据也会被清除。

------------------------------------ 删除数据的更新正常情况 ---------------------------------------

对于删除,您可以使用一些选项

  1. 删除特定型号的所有数据,请参阅doc realm.allObjects(MyModel.class).clear();
  2. 通过 (Realm API)[https://realm.io/docs/java/latest/api/io/realm/Realm.html#deleteRealm(io.realm.RealmConfiguration)] 从给定的 Realm 中删除全部数据(首先关闭所有实例!): Realm.deleteRealm(realmConfig);
  3. 或者直接删除Realm文件java API.

如果你真的很关心性能,你可以考虑将这些数据分离在一个Realm中,然后使用选项2或3来删除它们。通过 RealmConfiguration.

使用不同的领域,请参阅文档 here

------------------------------------ 按日期更新删除字段 ------------------------------------------ ----------

对于您的用户案例,这将是一个不错的选择:

  1. 向您的模型添加一个 Date 字段,并添加注释 @Index 以加快查询速度。

  2. Update/add 行并将修改日期设置为当前时间。

  3. 删除modifiedDate在当前日期之前的对象realm.where(MyModel.class).lessThan("modifiedDate", currentDate).findAll().clear()

注意:"The dates are truncated with a precision of one second. In order to maintain compatibility between 32 bits and 64 bits devices, it is not possible to store dates before 1900-12-13 and after 2038-01-19." 参见 current limitations. If you could modified the table in a very short time which the accuracy doesn't fit, consider to use a int field instead. You can get the column's max value by RealmResult.max()