Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 963
TramPamPam Avatar asked Oct 19 '22 09:10

TramPamPam


1 Answers

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.

like image 92
user3567929 Avatar answered Oct 21 '22 04:10

user3567929