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

First I check if self.statisticsArray.count == 0, then I create a new record, otherwise I update the existing value. When I create a new object, everything is fine, but when I try to update an existing one, it crashes with the following error:

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

But I do all this in one block .write, why does it cause such an error? I read that if I use .write(), I do not need to close the transaction. Can someone describe me why it falls?

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)
        })
     }
}
+6
source share
2 answers

self.statistics.summary = 250Must be inside a 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)
     })
}
+13
source

?

self.statistics.realm?.beginWrite()
self.statistics.summary = 250
do {
    try self.statistics.realm?.commitWrite()
} catch {
    print(error.localizedDescription)
}
0

Source: https://habr.com/ru/post/1629218/


All Articles