Search code examples
iosswiftrealm

Attempting to modify object outside of a write transaction - error in 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)
        })
     }
}

Solution

  • 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)
         })
    }