Delete an Object - Kotlin SDK
To delete an object from a realm:
- Open a write transaction with realm.write() or realm.writeBlocking().
- Query the transaction's mutable realm for the object you want to delete
with realm.query().
Specify the object type as a type parameter passed to
query()
. Filter the set of returned objects by specifying a query. To ensure your query returns the correct object, filter with unique identifying information such as a primary key value. - Delete the set of RealmResults returned by the query with realmResults.delete().
realm.write { // fetch the frog by primary key value, passed in as argument number 0 val frog: Frog? = this.query<Frog>("_id == $0", PRIMARY_KEY_VALUE).first().find() // call delete on the results of a query to delete the object permanently frog?.also { delete(it) } }
Note
You can only delete objects from a realm within a write transaction.