我正在尝试删除领域中的1个对象,但我无法执行此方法。有什么不对?
var realm = RLMRealm.defaultRealm()
realm.beginWriteTransaction()
var soo = Sample3()
soo.sampleKey = "edit1"
soo.id = 0
realm.deleteObject(soo)
realm.commitWriteTransaction()
println("deleted")
出现此错误......
swiftRealm[50559:847671] *** Terminating app due to uncaught exception 'RLMException', reason: 'Can only add an object to a Realm in a write transaction - call beginWriteTransaction on an RLMRealm instance first.'
答案 0 :(得分:4)
我有点困惑,您是否尝试addObject或deleteObject?我看到你创建了一个Sample3对象,我想这是一个RLMObject,但是当你想将addObject添加到Realm时,你只需要创建一个新的RLMObject。
如果要从Realm中删除对象,则应首先从Realm中获取对象,然后将其删除。类似的东西:
Sample3 *obj = [Sample3 objectsWithPredicate:[NSPredicate predicateWithFormat:@"sampleKey = %@ AND id = %d", @"edit1", 0]][0]
[realm deleteObject(obj)]
抱歉,我不熟悉Swift语法,所以上面的内容是Obj-c。 希望它有所帮助。
答案 1 :(得分:1)
Evan Chu是正确的,你正在创建一个新对象,然后在它被添加到领域之前要求删除它。
首先需要查询要删除的对象(假设它已经保存在领域中),即:
var objectToDelete = Sample3.objectsWhere("id == 0")
然后你可以删除这个对象
realm.beginWriteTransaction
realm.deleteObject(objectToDelete)
realm.commitWriteTransaction
答案 2 :(得分:0)
我的代码:
var hello = Sample3.objectsWhere("id = 0") // maybe: Sample3.objectsWhere("id = '0'") or Sample3.objectsWhere("sampleKey = 'edit1'")
let realm = RLMRealm.defaultRealm()
realm.beginWriteTransaction()
realm.deleteObject(hello.firstObject() as RLMObject)
realm.commitWriteTransaction()
设置:var hello = Sample3.objectsWhere("id == 0")
时。你好是一个RLMResults。它不是RLMObject,因此您无法删除此对象。您应该删除hello.firstObject()
之类的RLMObject
更多信息:http://realm.io/docs/cocoa/0.87.1/api/Classes/RLMResults.html#//api/name/realm