deleteObject在Realm中不起作用

时间:2015-04-06 09:51:31

标签: ios objective-c ios7 realm

这是我的代码,我无法弄清楚我做错了什么。我正如文件中所说的那样做 http://realm.io/docs/cocoa/0.91.1/#deleting-objects

       // Delete Current Object
        RLMRealm *realm = RLMRealm.defaultRealm;

        [realm beginWriteTransaction];
        EBooks *eBookdb = [[EBooks alloc]init];
        eBookdb.eBook_ID = [NSString stringWithFormat:@"%@",self.eBookID];
        eBookdb.status = @"canceled";
        [EBooks createOrUpdateInRealm:realm withObject:eBookdb];

        [realm commitWriteTransaction];

        //=> break point here before crash      

        [realm beginWriteTransaction];
        [realm deleteObject:eBookdb];
        [realm commitWriteTransaction];

并且应用程序在断点之后崩溃并出现以下错误

  

'只能从它所属的领域中删除一个对象。'

1 个答案:

答案 0 :(得分:5)

问题在于您尝试删除独立的EBooks对象,而不是继承在Realm中的对象。如果您将代码更改为以下内容,则应该可以正常工作:

// Delete Current Object


RLMRealm *realm = RLMRealm.defaultRealm;

[realm beginWriteTransaction];
EBooks *eBookdb = [[EBooks alloc]init];
eBookdb.eBook_ID = [NSString stringWithFormat:@"%@",self.eBookID];
eBookdb.status = @"canceled";
eBookdb = [EBooks createOrUpdateInRealm:realm withObject:eBookdb];

[realm commitWriteTransaction];  

[realm beginWriteTransaction];
[realm deleteObject:eBookdb];
[realm commitWriteTransaction];