我有一个 RealmObject Notes:
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 对象所做的所有编辑。因此,每当有人编辑注释时,我希望前一个注释存储在编辑历史记录中,同时显示最新的注释。我试过这种方式:
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();
但是每当我更新新笔记时,编辑历史中的上一个笔记也会更新。有没有办法克隆 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);
我使用以下代码在 swift 3 中克隆
斯威夫特 3
要在swift
中创建用户对象的克隆,只需使用
let newUser = User(value: oldUser)
;
注: 不会保留新用户对象。