将独立对象添加到RealmList [英] Adding standalone-objects to a RealmList

查看:178
本文介绍了将独立对象添加到RealmList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将独立对象添加到已经存在于领域中的RealmObject的RealmList中?

Is it possible to add standalone objects to a RealmList of an RealmObject already persisted in a realm?

嗯,我知道它不起作用,因为我得到了NPE ( object.row.getIndex():RealmList:94

Well, I know it doesnt work, because I get NPEs at (object.row.getIndex():RealmList:94)

我想做的是:

mRealm.beginTransaction;
contact.getEmails().add(new Email());
mRealm.commitTransaction;

因为在那个特定时刻我无法访问Realm(我可以让它工作,但是我必须重写一些结构),例如:

Because at that specific moment I dont have access to a Realm (well I could make it work, but I would have to rewrite some structures), for example:

//In Activity
Contact contact = Realm.where(Contact.class).equalsTo("name","pete").findAll().first();
mRealm.beginTransaction;
UpdateHelper.update(contact);
mRealm.commitTransaction;

//Helper class some else package
public static void update(Contact contact) {
    //do update stuff
    contact.getEmails().add(new Email());
}

`

推荐答案

来自Realm的Christian。
不,目前这是不可能的。这是一个有趣的用例。
我们有一个 Realm.copyToRealm()方法的原因是为了让你真正明确不再使用你的旧对象。允许将独立对象添加到已经存在的列表中会降低透明度。您还需要在写入事务中进行此操作。在方法调用中添加对Realm的引用可能是解决它的最佳方法。

Christian from Realm here. No, currently that is not possible. It is an interesting use case though. The reason we have a Realm.copyToRealm() method is to make it really explicit that you should no longer use your old object. Allowing to add standalone objects to already persisted lists would make that less transparent. You also still need it to happen inside a write transaction. Adding a reference to the Realm in your method call would probably be the best way to solve it.

//In Activity
realm.executeTransaction(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {
        Contact contact = realm.where(Contact.class)
                               .equalTo("name","pete")
                               .findFirst();
        if(contact != null) {
            UpdateHelper.update(contact, realm);
        }
    }
});

//helper method
public static void update(Contact contact, Realm realm) {
    //do update stuff
    Email email = realm.copyToRealm(new Email());
    contact.getEmails().add(email);
}

这篇关于将独立对象添加到RealmList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆