Attempting to modify object outside of a write transaction - call beginWriteTransaction on an RLMRealm instance first


#1

Hi, I want add record any tap a button. I write this code to add object in Realm database but the App crashed and return this message: “Attempting to modify object outside of a write transaction - call beginWriteTransaction on an RLMRealm instance first”
I use RealSwift

func save(){
let realm = try! Realm()
try! realm.write {
realm.add(myClass)
try! realm.commitWrite()
}
App crashing the second time I try to rewrite on Realm


#2

There are a few issues with your code.

  • don’t use force try - use try-catch instead. You can handle the realm errors in that way, now you will crash.
  • You are crashing, because you try to modify a realm object (myClass) somewhere, outside a write transaction - as the error said. Once you add an object to a realm, then that realm will manage that object. With the correct architect, you can fix all of these issues.
  • you should not have unnecessary commitWrite-s. The commitWrite will call after a write transaction ends.

#3

thanks! but about this:
You are crashing, because you try to modify a realm object (myClass) somewhere, outside a write transaction - as the error said. Once you add an object to a realm, then that realm will manage that object. With the correct architect, you can fix all of these issues.

if I understand, I can add object to realm only once and I can’t close write transaction during View alive?


#4

No. You can add an object twice ( with different primaryKey), and you can close a write transaction, but you dont neet to write realm.commitWrite() -> thats an unnecessary save.

If you want to update an object, that was added to a realm, then query it out then modify it in a write transaction.


#5

Can you show a code example please?


#6

#7

I had this snippet on my stickies - a safe way to work with writing data to realm, including error handling showing different info about the error, if one occurs.

    do {
        let realm = try Realm()

        try! realm.write {
            realm.add(myClass)
        }

    } catch let error as NSError {
        print("Error: " + error.localizedDescription) 
        let err = error.code
        print(err)
        let t = type(of: err)
        print(t)
    }

Keeping in my myClass will need to have a unique primary key if it uses one.