Problem trying to update object instance with Realm

Asked

Viewed 109 times

0

I made a request in the local database and received an array with the data. Then I run the array with looping for, looking for an object with a specific id, when locating the object I try to update a property, but Realm triggers the following error:

*** Terminating app due to uncaught Exception 'Rlmexception', Reason: 'Attempting to Modify Object Outside of a write transaction - call beginWriteTransaction on an Rlmrealm instance first.'

Code that generates the error:

var arrayObjects: Results<MyModel>?

viewDidLoad(){

    arrayObjects = managerLocalDB.getAllData()

}

// Depois ...

    func registerNewStatus(status: Bool, id: Int) {

        for abrTmp in arrayObjects!{

            if abrTmp.id == id{

                abrTmp.selecionado = status

            }

        }

    }

From what I’ve seen, Realm updates the instances of your requests by having modifications to the record. But I don’t want the record to be updated until I send the data to the server.

1 answer

1


To update a Realm object you have to define one of the attributes with the object id, or rather, the primary key of this object:

Object primary key example

class Person: Object {
    dynamic var id = 0
    dynamic var name = ""

    override static func primaryKey() -> String? {
        return "id"
    }
}

Placing the object class with a primaryKey You have to make the object be updated when you want. Whenever you want to do a data update you should then mark the transfer for the obejto to be updated.

let cheeseBook = Book()
cheeseBook.title = "Cheese recipes"
cheeseBook.price = 9000
cheeseBook.id = 1

// Updating book with id = 1
try! realm.write {
  realm.add(cheeseBook, update: true)
}

In this example above, it will update the value of the object that has the id equal to 1

In case you didn’t want to create a new object so make all its parser has an easier way.

Example below it updates the boolean value of an obejto in Realm.

let objeto= realm.objects(ObjetoMeu).first

try! realm.write {     
   objeto!.valorBool= true                
}

For more information I recommend taking a look at the documentation which is very good:

https://realm.io/docs/swift/latest/#updating-Objects

  • I came to the same conclusion after researching a little, but you already said the answer!! Thank you Lucas!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.