使用Realm尝试删除一个对象会引发异常(“只能在写事务中将对象添加到Realm中……") [英] Using Realm trying to delete one object raises an exception ('Can only add an object to a Realm in a write transaction...')
问题描述
我正在尝试删除领域中的1个对象,但无法执行此方法.有什么不对?
I'm trying to delete 1 object in realm but I can't perform this method. Is there something wrong?
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.'
推荐答案
我有点困惑,您是要添加对象还是删除对象?我看到您创建了一个Sample3对象,我想它是一个RLMObject,但是恕我直言,您仅在要将Object添加到Realm时才创建一个新的RLMObject.
I am a little confused, are you trying to addObject or deleteObject? I saw that you created a Sample3 object which I suppose is an RLMObject, but IMHO you only create a new RLMObject when you want to addObject to Realm.
如果要从Realm中删除对象,则应先从Realm中获取该对象,然后再将其删除.像这样:
If you want to delete an object from Realm, you should fetch the object from Realm first, then delete it. Something like:
Sample3 *obj = [Sample3 objectsWithPredicate:[NSPredicate predicateWithFormat:@"sampleKey = %@ AND id = %d", @"edit1", 0]][0]
[realm deleteObject(obj)]
对不起,我不熟悉Swift语法,因此上面的Obj-c中. 希望对您有所帮助.
Sorry, I am not familiar with Swift syntax, so the above in Obj-c. Hope it helps.
这篇关于使用Realm尝试删除一个对象会引发异常(“只能在写事务中将对象添加到Realm中……")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!