I want to create an edit view for an existing object model in a Realm.io database. The view controller has a save button which should persist the changes and a cancel button which should discard the changes.
I can not modify a RLMObject
outside of a write transaction, so what is the recommended method of temporarily modifying a RLMObject
enabling me to discard the changes later if necessary?
You could pass your realm object in to your edit view controller as an in-memory object to do your editing. Like so:
RLMRealm *realm = [RLMRealm defaultRealm];
[realm beginWriteTransaction];
[StringObject createInDefaultRealmWithObject:@[@"a"]];
[realm commitWriteTransaction];
StringObject *obj = [[StringObject alloc] initWithObject:[[StringObject allObjects] firstObject]];
XCTAssertEqualObjects(obj.stringCol, @"a");
obj.stringCol = @"b"; // not in a write transaction
XCTAssertEqualObjects(obj.stringCol, @"b");
If the user presses "Save", you can then call createOrUpdateInDefaultRealmWithObject:
and pass in your in-memory object, which will then pass in all the values and update that object in Realm. Note that your object must have a primary key for this to work.
If the user presses "Cancel", you can just discard that in-memory object as if nothing happened.
Note that we intend to add transaction rollback functionality in the future, which will simplify this pattern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With