Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deleteObject doesn't work in Realm

Here is my code and I can't figure out what I'm doing wrong . I'm doing as it says in the document 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];

and the app crashes after the breakpoint with the following error

'Can only delete an object from the Realm it belongs to.'

like image 399
Treasure Priyamal Avatar asked Apr 06 '15 09:04

Treasure Priyamal


1 Answers

The issue is that you're trying to delete the standalone EBooks object, rather than the one persisted in the Realm. If you change your code to the following, it ought to work:

// 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];
like image 117
segiddins Avatar answered Sep 20 '22 12:09

segiddins