且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Realm尝试删除一个对象会引发异常(“只能在写事务中将对象添加到Realm中……")

更新时间:2023-12-01 20:40:22

我有点困惑,您是要添加对象还是删除对象?我看到您创建了一个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.