Using a Realm trying to delete a single object throws an exception ("Can only add an object to the Realm in a write transaction ...")

I am trying to delete 1 object in a scope, but I am unable to complete this method. Is there something wrong here?

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

+3


source to share


3 answers


I'm a little confused, are you trying to add an Object or deleteObject? I saw that you created a Sample3 object, which I assume is an RLMObject, but IMHO you only create a new RLMObject when you want to add an object to the Realm.

If you want to remove an object from the Realm, you must first extract the object from the Realm and then remove it. Something like:



Sample3 *obj = [Sample3 objectsWithPredicate:[NSPredicate predicateWithFormat:@"sampleKey = %@ AND id = %d", @"edit1", 0]][0]
[realm deleteObject(obj)]

      

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

+4


source


Evan Chu is right, you create a new object and then ask it to be removed before it is added to the Realm.

First you need to query for the object you want to delete (if it is already stored in the scope), that is:

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

      



Then you can delete this object

realm.beginWriteTransaction
realm.deleteObject(objectToDelete)
realm.commitWriteTransaction

      

+1


source


My code:

var hello   =   Sample3.objectsWhere("id = 0") // maybe: Sample3.objectsWhere("id = '0'") or        Sample3.objectsWhere("sampleKey = 'edit1'")
let realm = RLMRealm.defaultRealm()
realm.beginWriteTransaction()
realm.deleteObject(hello.firstObject() as RLMObject)
realm.commitWriteTransaction()

      

When you set: var hello = Sample3.objectsWhere("id == 0")

. Hi - RLMResults. It is not an RLMObject, then you cannot delete this object. You have to remove the RLMObject, for example hello.firstObject()

More info: http://realm.io/docs/cocoa/0.87.1/api/Classes/RLMResults.html#//api/name/realm

0


source







All Articles