如何在RealmObject属性中更新RealmObject?

时间:2018-04-04 09:21:59

标签: android realm insert-update

Message extends RealmObject{
Attachment attachment;
}

Attachment extends RealmObject{
int state;
}

我想在附件中更新状态。我沿着这样的道路前进:

RealmResults<Message> allMessages = mRealm.where(Message.class)
                .isNotNull("attachment")
                .in("attachment.state", new Integer[]{INTERRUPTED,PENDING})
                .findAll();

if (allMessages != null && allMessages.size() > 0) {
    for (Message message : allMessages) {
        Attachment attachment = message.getAttachment();
        attachment.setState(IDLE);
    }
}

有没有办法通过直接附件来更新状态?

1 个答案:

答案 0 :(得分:1)

庵。

try(Realm r = Realm.getDefaultInstance()) {
    r.executeTransaction((realm) -> {
        RealmResults<Attachment> attachments = realm.where(Attachment.class)
           .in("state", new Integer[]{INTERRUPTED,PENDING})
           .findAll();
        for(Attachment attachment: attachments) {
            attachment.setState(IDLE);
        }
    });
}