In my project I need to send Realm Object in Request body. Before this operation, I need to replace some of values in object variables with another.
But I don't need to save new values, before I get success response from server.
In case when I don't opened transaction on changing I get error
'Attempting to modify object outside of a write transaction - call beginWriteTransaction on an RLMRealm instance first.'
So, is there any way to modify Realm object without instant saving, but rather 'saving on success' case?
You can do it in this way:
clone your stored realm object:
var editableObject: MyRealmObjectClass?
editableObject = MyRealmObjectClass(value: alreadyStoredObject)
Then, all modification you need, you do over this cloned copy:
editableObject.someProper = newValue
Then you send this copy in request body. And after success response from server, you do backward:
alreadyStoredObject = MyRealmObjectClass(value: editableObject)
And after this you can write updated object into local db:
let realm = try! Realm() try? realm.write { realm.add(alreadyStoredObject, update: true) }
primaryKey of alreadyStoredObject won't be changed.
editableObject won't be saved and eventually will be discarded, after you leave your ViewController.
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