我尝试更新值两次,但出现运行时错误。我的代码如下
我的模型是
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"
}
}
函数是
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")
}
}
应用在打印 entering if 8
后崩溃
错误是
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
我做错了什么?
最佳答案
在第一个 write
block 之后,您的 helperNerd
对象被添加到 Realm ,因此它不再是一个独立的对象。
存储对象的任何更新都应该在事务内部发生,但是您在 write
block 之外分配 helperNerd.happened = false
,因此会发生异常。
所以只需重写 if
block 如下:
if helperNerd.counter == 8 {
let realm = try! Realm()
print("entering if 8")
try! realm.write {
helperNerd.happened = false
// note that add() is not needed anymore
// because we're sure object exists in realm
}
print("updated inside if 8")
}
关于ios - Realm - 无法更新值 2 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34529488/