2016-09-25 65 views
1

我有一个RealmObjectUser,我存储在一个单例中并访问整个应用程序 - 它是在UI线程中检索的。该对象表示登录的用户,并且与Item类具有一对多关系。当在交易中更改它时,例如:从另一个线程读RealmObject

这不起作用,因为我在另一个线程中发生的事务内部访问它。为了澄清一下,我需要做的是将用户的id存储在事务之外,然后在进行查询时访问该事务中存储的变量,如下所示?

Integer userId = UserSingleton.getUser().getId(); 
Integer classId = mItem.getClassId(); 
RealmSingleton.getUserInstance().executeTransactionAsync(new Realm.Transaction() { 
     @Override 
     public void execute(Realm realm) { 
      User user = realm.where(User.class).equalTo("mId",userId).findFirst(); 
      user.deleteItem(classId); 
     } 
    }); 
+0

这听起来是对的,虽然我对“deleteItem”的实现感到怀疑 – EpicPandaForce

+0

@EpicPandaForce它只是一个遍历'User'的Item'列表的循环,直到它找到一个具有匹配的类id,以及何时它找到了一个它称之为“RealmList.deleteItemAt”的匹配 - 就是这样。 – shoe

+0

啊等等https://realm.io/docs/java/latest/api/io/realm/RealmList.html#deleteFromRealm-int-?虽然我更喜欢获取元素并在其上调用deleteFromRealm,但它应该可以工作。这是一个奇怪的问题。 – EpicPandaForce

回答

2

是的,这是正确的。您无法访问多个线程上的对象,因此在您的情况下存储对该ID的引用并使用它来重新查询该对象是正确的方法。