gpt4 book ai didi

android - 制作 RealmObject 的克隆,而不会在我更新数据时影响它

转载 作者:搜寻专家 更新时间:2023-11-01 07:50:14 24 4
gpt4 key购买 nike

我有一个 RealmObject 注释:

public class Notes extends RealmObject {

private String title;
private String text;
private Date updatedDate;
private RealmList<Notes> editHistories = new RealmList<>();

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public String getText() {
return text;
}

public void setText(String text) {
this.text = text;
}

public Date getUpdatedDate() {
return updatedDate;
}

public void setUpdatedDate(Date updatedDate) {
this.updatedDate = updatedDate;
}

public RealmList<Notes> getEditHistories() {
return editHistories;
}

public void setEditHistories(RealmList<Notes> editHistories) {
this.editHistories = editHistories;
}
}

我想跟踪对 Notes 对象所做的所有编辑。因此,每当有人编辑 Note 时,我都希望在显示最新的同时将前一个存储在 editHistories 中。我这样试过:

RealmResults<Notes> results = realm.where . . .;
Notes prevNote = results.get(0);
Notes newNote = realm.copyToRealm(prevNote);
newNote.getEditHistories().add(prevNote);
// set other parameters

这样:

RealmResults<Notes> results = realm.where . . .;
Notes prevNote = results.get(0);
Notes newNote = realm.createObject(Notes.class);
//set other parameters
newNote.setEditHistories(prevNote.getEditHistories());
newNote.getEditHistories().add(prevNote);
prevNote.removeFromRealm();

但是每当我更新 newNote 时,editHistories 中的 prevNote 也会更新。有什么方法可以克隆 prevNote,使其与 newNote 分开,并且不会受到我对后者所做的任何更改的影响?

任何建议都将受到热烈欢迎和赞赏!

最佳答案

copyToRealm() 不会复制 Realm 中已有的对象。复制部分是对 Realm 中对象复制的引用,不是,但我明白为什么它会变得有点困惑,我们的 Javadoc 可能应该更好地指定行为。

您可以使用的一种解决方法是确保首先分离对象,如下所示:

RealmResults<Notes> results = realm.where . . .;
// This creates a detached copy that isn't in the Realm
Notes prevNote = realm.copyFromRealm(results.get(0));
// add() will automatically do a copyToRealm if needed
newNote.getEditHistories().add(prevNote);

关于android - 制作 RealmObject 的克隆,而不会在我更新数据时影响它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35775627/

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