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)
})
}
}
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)
}
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)
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With