I try to update value two times and i get run time error. My code is following
My model is
class Achievement: Object {
dynamic var name:String = ""
dynamic var counter:Int = 0
dynamic var happened:Bool = false
convenience init(name:String, counter:Int, happened:Bool) {
self.init()
self.name = name
self.counter = counter
self.happened = happened
}
override class func primaryKey() -> String {
return "name"
}
}
Function is
func checkHelperNerdAch() {
var helperNerd = Achievement()
let realm = try! Realm()
var results = realm.objects(Achievement).filter("name = 'helperHelperNerd'")
for element in results {
helperNerd = Achievement(name: element.name, counter: element.counter, happened: element.happened)
}
helperNerd.counter++
try! realm.write {
realm.add(helperNerd, update: true)
}
if helperNerd.counter == 8 {
let realm = try! Realm()
print("entering if 8")
helperNerd.happened = false
try! realm.write {
realm.add(helperNerd, update: true)
}
print("updated inside if 8")
}
}
App crashes after printing entering if 8
Error is
2015-12-30 15:09:00.307 AppName[3215:640021] * Terminating app due to uncaught exception 'RLMException', reason: 'Attempting to modify object outside of a write transaction - call beginWriteTransaction on an RLMRealm instance first.' * First throw call stack: (0x2516c10b 0x24912e17 0xf6bf0b 0x1586c8 0x6cb5c 0x6cd38 0x29556043 0x29545ac3 0x26450c7f 0x26450f71 0x2512f68f 0x2512f27d 0x2512d5eb 0x25080bf9 0x250809e5 0x262ccac9 0x29310ba1 0x6db90 0x24d2f873) libc++abi.dylib: terminating with uncaught exception of type NSException
What am I doing wrong ?