Treasure Priyamal
Treasure Priyamal

Reputation: 307

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.'

Upvotes: 7

Views: 3105

Answers (1)

segiddins
segiddins

Reputation: 4120

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];

Upvotes: 5

Related Questions