我有一个 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 对象所做的所有编辑。因此,每当有人编辑注释时,我都希望将前一个注释存储在 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/