TramPamPam
TramPamPam

Reputation: 51

Can I edit Realm object without transaction in Swift?

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

Answers (2)

user3567929
user3567929

Reputation: 107

You can do it in this way:

  1. clone your stored realm object:

    var editableObject: MyRealmObjectClass?

    editableObject = MyRealmObjectClass(value: alreadyStoredObject)
    
  2. Then, all modification you need, you do over this cloned copy:

editableObject.someProper = newValue

  1. Then you send this copy in request body. And after success response from server, you do backward:

    alreadyStoredObject = MyRealmObjectClass(value: editableObject)

  2. 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

2ank3th
2ank3th

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

Related Questions