0

I would like to know how to create a copy of the realm object which is previously retrieved from the store. After i would store the new object with a incremented id. The problem is that the mentioned RealmObject is created in an early time of realm so no PrimaryKey or such is present.

Thank you for your suggestions. Daniel

drindt
  • 901
  • 10
  • 15

4 Answers4

5

Try this:

Product productCopy = realm.copyFromRealm(product);
productCopy.setId(product.getId() + 1);
realm.beginTransaction();
productCopy = realm.copyToRealm(productCopy);
realm.commitTransaction();

productCopy - is a new object, attached to realm with incremented ID and the same values in the fields.

Grimmy
  • 2,041
  • 1
  • 17
  • 26
1

you have to create another object and add the new object to realm inside a realm Transaction

  OriginalRealmObject *originalActivity = [OriginalRealmObject objectForPrimaryKey:@"primary key"];

 OriginalRealmObject* clonedObject   = [[OriginalRealmObject alloc] initWithValue:originalActivity];


  [realm beginWriteTransaction];

  clonedObject.id            = originalActivity.id+1; //make sure is an int property


  [OriginalRealmObject createOrUpdateInRealm:realm withValue:clonedObject];
  [realm commitWriteTransaction];
Spaceghost
  • 45
  • 3
1

I am not sure if i understand you question correctly, if what you want is to copy a RealmObject and assign a different primary key and store it, you can try this:

// Get your original RealmObject
YourModel obj1 = realm.where(YourModel.class).findFirst()
// Create a RealmObject instance without proxy, setters won't write to db
YourModel obj2 = new YourModel();
obj2.setField1(obj1.getField1());
obj2.setField2(obj1.getField2());
obj2.setPrimaryKey(obj1.getPrimaryKey()+1);

realm.beginTransaction();
// This will write obj2 to Realm. And the returned YourModel instance 
// will be RealmObject with proxy. Setters will write to Realm automatically.
obj2 = realm.copyToRealmOrUpdate(obj2);
realm.commitTransaction();

Doc here might help.

beeender
  • 3,555
  • 19
  • 32
-1

You can do a workaround, encode in JSON and then decode back, and you have true deep copy. Though not an ideal solution.

Have look at this swift code if it helps, check out second step: here

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
ImShrey
  • 380
  • 4
  • 12