Using Realm trying to delete one object raises an exception ('Can only add an object to a Realm in a write transaction...')

11,598

Solution 1

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.

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

Sorry, I am not familiar with Swift syntax, so the above in Obj-c. Hope it helps.

Solution 2

Evan Chu is correct, you are creating a new object and then asking to delete it before it has even been added to the Realm.

You first need to query for the object you want to delete (assuming it's already saved in the realm) ie:

var objectToDelete = Sample3.objectsWhere("id == 0")

Then you can delete this object

realm.beginWriteTransaction
realm.deleteObject(objectToDelete)
realm.commitWriteTransaction
Share:
11,598
zapKILIG
Author by

zapKILIG

Updated on July 24, 2022

Comments

  • zapKILIG
    zapKILIG almost 2 years

    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")
    

    It has this error...

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