gpt4 book ai didi

android - 从 Realm 分离 RealmObject/将托管 RealmObject 转换为非托管对象

转载 作者:可可西里 更新时间:2023-11-01 19:10:36 26 4
gpt4 key购买 nike

我想从它的 Realm 中“分离”一个 RealmObject,这意味着我希望能够从一个方法中返回一个 RealmObject并能够在我关闭 Realm 实例后使用它。

像这样:

public Person getPersonWithId(final Context context, final String personId){
Realm realm = Realm.getInstance(context);
Person person = realm.where.....;
realm.close();
return person;
}

目前 getPersonWithId(mContext, personId).getName() 将按预期返回错误。

拥有托管对象也意味着该对象是不可变的(无法修改),因此任何更新对象的方法如 person.setName(String name) 都将失败,因为该对象是托管的对象。

我希望有这样的方法 Person person = person.detachFromRealm();

有人知道这个问题的解决方案/解决方法吗?

最佳答案

Android Realm 现在支持附加和分离 Realm 对象。所以你可以这样做:

RealmObject objectCopy = realm.copyFromRealm(RealmObject object);

以下是文档中的详细信息:

Instances of Realm objects can be either managed or unmanaged.

Managed objects are persisted in Realm, are always up to date and thread confined. They are generally more lightweight than the unmanaged version as they take up less space on the Java heap.

Unmanaged objects are just like ordinary Java objects, they are not persisted and they will not be updated automatically. They can be moved freely across threads.

It is possible to convert between the two states using Realm.copyToRealm() and Realm.copyFromRealm()

关于android - 从 Realm 分离 RealmObject/将托管 RealmObject 转换为非托管对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32256034/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com