从另一个线程读取 RealmObject [英] Reading a RealmObject from another thread
问题描述
我有一个 RealmObject
User
,我将它存储在单例中并在整个应用程序中访问——它是在 UI 线程上检索的.该对象代表已登录的用户,并与 Item
类具有一对多关系.在事务中更改它时,例如:
I have a RealmObject
User
that I store in a singleton and access throughout the application -- it was retrieved on the UI thread. The object represents the logged in user, and has a one-to-many relationship with the Item
class. When changing it in a transaction such as in:
RealmSingleton.getUserInstance().executeTransactionAsync(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
User user = realm.where(User.class).equalTo("mId",UserSingleton.getUser().getId()).findFirst();
user.deleteItem(mItem.getClassId());
}
});
这行不通,因为我正在另一个线程中发生的事务内部访问它.只是为了澄清一下,我在这里需要做的是将用户的 id 存储在事务之外,然后在进行查询时访问事务中存储的变量,就像这样?
This won't work because I'm accessing it inside of the transaction that occurs in another thread. Just to clarify, what I need to do here is store the user's id outside of the transaction and then access that stored variable within the transaction when making the query, like so?
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);
}
});
推荐答案
是的,没错.您无法在多个线程上访问对象,因此在您的情况下,存储对 ID 的引用并使用它来重新查询对象是正确的方法.
Yes, that is correct. You cannot access an object on multiple threads, so in your case storing a reference to the ID and use that to requery the object is the right approach.
这篇关于从另一个线程读取 RealmObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!