android - 克隆 RealmObject 而不会在更新数据时受到影响

标签 android realm

我有一个 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/

相关文章:

android - 如何使微调对话框显示当前选定的项目?

java - 来自服务的通知

java - 按下按钮的 Android Firebase RecyclerView 出现无法解释的错误

android - Firebase 可扩展通知在应用程序处于后台时显示图像

java - Android 在准备Asunc 时停止媒体播放器

ios - 我的 swift - Realm 应用程序因不兼容的库版本问题而崩溃

android - Realm 比 SQLite 花费更多时间进行读写

swift - 空RLMArray的 Realm 查询

android - Image Url 存储在相机和图库 Intent 的 Realm 中,但在 ListView 中看不到

java - 同时使用大写和小写搜索