Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attempting to modify object outside of a write transaction - error in Realm

Tags:

ios

swift

realm

At first, I'm checking if self.statisticsArray.count == 0 then I create a new record, else I'm updating the exist value. When I create a new object, all okay, but when I'm trying to update the exist one, it crashes with the next error:

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

But I do it all in one .write block, why it rises such error? I read that if I use .write(), then I do not need to close the transaction. Can anyone describe me why it crashes?

if self.statisticsArray.count == 0 {
     self.statistics.summary = 250

     try! self.realm.write({
         self.realm.add(self.statistics)
         self.realm.add(record)
     })
 } else {
     if day == self.statisticsArray.last?.date {
         try! self.realm.write({
             self.realm.objects(Statistics).last?.summary += 250
             self.realm.add(record)
         })
     } else {
        try! self.realm.write({
             self.statistics.summary = (self.statisticsArray.last?.summary)! + 250
             self.realm.add(self.statistics)
             self.realm.add(record)
        })
     }
}
like image 725
John Doe Avatar asked Feb 17 '16 16:02

John Doe


2 Answers

I also had such a problem, and I decided like this.

let model = RealmModel()
model.realm?.beginWrite()
model.property = someValue
do {
    try model.realm?.commitWrite()
} catch {
    print(error.localizedDescription)
}
like image 190
Ruben Nahatakyan Avatar answered Sep 24 '22 11:09

Ruben Nahatakyan


self.statistics.summary = 250 needs to be within the write transaction. It should look like this:

if self.statisticsArray.count == 0 {

     try! self.realm.write({
         self.statistics.summary = 250
         self.realm.add(self.statistics)
         self.realm.add(record)
     })
}
like image 45
yoshyosh Avatar answered Sep 23 '22 11:09

yoshyosh