Reputation: 135
I have a 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;
}
}
I want to keep track of all the edits made to the Notes object. So, whenever someone edits the Note, I want the previous one to be stored in editHistories while I display the most recent. I tried it this way:
RealmResults<Notes> results = realm.where . . .;
Notes prevNote = results.get(0);
Notes newNote = realm.copyToRealm(prevNote);
newNote.getEditHistories().add(prevNote);
// set other parameters
And this way:
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();
But whenever I update newNote, the prevNote in editHistories gets updated too. Is there any way to clone prevNote such that it will be separate from newNote and won't be affected by any changes I make to the latter?
Any suggestions would be most welcome and appreciated!
Upvotes: 2
Views: 1189
Reputation: 6722
I used the following code to clone in swift 3
Swift 3
To create a clone of user object in swift
just use
let newUser = User(value: oldUser)
;
Note: The new user object is not persisted.
Upvotes: 0
Reputation: 20126
copyToRealm()
doesn't make a copy of objects already in the Realm. The copy part is a reference to the copying of objects not in Realm, but I can see why it can get slightly confusing and our Javadoc should probably specify the behaviour better.
One work-around you can use is to make sure the object is detached first, so like this:
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);
Upvotes: 4