Reputation: 51
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?
Upvotes: 5
Views: 1662
Reputation: 107
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.
Upvotes: 6
Reputation: 3109
You can begin a transaction using realm.beginWrite()
and make the changes you want to make. If server call is a success then you can commit the transaction realm.commitWrite()
or else cancel the transaction realm.cancelWrite()
.
Upvotes: -1