John Doe
John Doe

Reputation: 821

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

Upvotes: 12

Views: 21072

Answers (2)

Ruben Nahatakyan
Ruben Nahatakyan

Reputation: 408

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

Upvotes: 3

yoshyosh
yoshyosh

Reputation: 14086

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

Upvotes: 22

Related Questions