如何持久化引用的 RealmObjects

How to persist referenced RealmObjects

考虑以下 RealmObject 子类

public class TimeSlot extends RealmObject
{
 @PrimaryKey
 private int value = 0;
 private int hits = 0;

 @LinkingObjects("ats") private final RealmResults<Visit> visits = null;

 public TimeSlot(){}

 public TimeSlot(int time)
 {
  super();
  value = time;
 } 

  ...
}

public class Visit extends RealmObject
{
 private RealmList<TimeSlot> timeslots = null;

 public Visit()
 {
  super();
  timeslots = new RealmList<TimeSlot>();
 }

 public void addTimeSlot(TimeSlot ts) throws Exception
 {
  this.timeslots.add(ts);
  try
  {
   myRealm.beginTransaction();
   myRealm.copyToRealmOrUpdate(this,ImportFlag.valueOf("CheckSameValuesBeforeSet"));
   myRealm.commitTransaction();
  }
  catch(Exception e)
  {
   myRealm.cancelTransaction();
   throw e;
  }  
 } 
}  

我在代码的其他地方执行了以下操作

myVisit.addTimeSlot(new TimeSlot(30));

将新的 TimeSlot 添加到 Visit 对象的现有实例,myVisit。您会注意到,在 addTimeSlot 中,我正在将修改后的 Visit 实例复制到 Realm。我的问题 - 这样做还会保留新创建的 TimeSlot 对象吗?

相关问题 - 当我从 Realm 检索 myVisit 时,是否可以保证 myVisit.timeslots 中的 TimeSlot 对象的顺序与我添加它们时的顺序相同?

你的大部分问题都在 Realm 文档中得到了解答,如果你知道去哪里找。主要文档中暗示了很多这些问题,然后您需要找到正确的 API 页面。有时只是尝试一下。

You will note that in addTimeSlot I am copying the modified Visit instance to Realm. My question - doing so will also persist the freshly created TimeSlot object?

没错。 copyToRealmOrUpdate 状态的文档:"This is a deep copy or update i.e., all referenced objects will be either copied or updated."

虽然你引入了一个潜在的问题。第一行 addTimeSlot 立即修改 Visit 对象。在 Visit 对象不受管理的情况下,或者如果您在调用 addTimeSlot 之外启动了 Realm 事务,这很好。但如果不是这种情况,那么您将收到有关 'Attempting to modify object outside of a write transaction' 的异常。您的方法依赖于您始终对对象的非托管版本进行操作,并手动将每个更改复制回 Realm。这并不是真正推荐的方法,因为您引入了对象不同步的可能性。最好始终处理托管对象。

您还访问了一个名为 myRealm 的变量,我认为它是对您的领域的全局引用。请注意,在托管对象的情况下,您可以访问 getRealm() 函数来检索对象的领域并避免使用 globals/passing 参数。

所以,更好的做法是:-

  1. 创建领域时将 Visit 添加到领域
  2. addTimeSlot 中,使用 getRealm() 的结果来验证 Visit 是否被管理。如果是这样,请将 TimeSlot 添加到 Realm 和 RealmList。

我对您的 TimeSlot 主键的工作方式很感兴趣。

无论如何,回到你的问题。

when I retrieve myVisit from Realm is there a guarantee that the TimeSlot objects in myVisit.timeslots will be in the same order as when I added them?

是的。订购了 RealmList。您可以将元素添加到末尾或使用 RealmList 插入。如果没有存储订单,这显然是多余的。参见 the docs

The docs mention that unmanaged objects are like simple POJOs. From what I understand if I create a RealObject subclass instance and never bother copying it to a Realm it will stay "unmanaged".

正确。

But then what happens if I add it to a RealmList instance that is part of a "managed" RealmObject?

已对此进行讨论 here。那么您的列表就是一个托管领域列表,并且此声明适用:

It is possible to add unmanaged objects to a RealmList that is already managed. In that case the object will transparently be copied to Realm using Realm.copyToRealm(RealmModel, ImportFlag...) or Realm.copyToRealmOrUpdate(RealmModel, ImportFlag...) if it has a primary key.

请注意,您对该对象的现有引用是对该对象的非托管版本,所以要小心。更改其字段不会更改托管版本。此时最好丢弃非托管版本并仅处理托管对象。

我明白你为什么感到困惑了。希望对您有所帮助。