Problem trying to update object instance with Realm

0

I made a request on 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, however Realm throws 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 have seen, Realm updates the instances of your requests when you have modifications to the registry. But I do not want the registry to be updated until it sends the data to the server.

    
asked by anonymous 29.04.2016 / 02:16

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 to update when you want. Whenever you want to do a data refresh you should then check the lock for the object 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, it will update the value of the object that has id equal to 1

If you did not want to create a new object so that your whole parser would have an easier way.

Example below it updates the boolean value of an object 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 that is very good:

link

    
29.04.2016 / 15:18