How to Easily Delete All Objects in a Realm

How can I easily delete all objects in a Realm

Use deleteAll():

let realm = try! Realm()
try! realm.write {
realm.deleteAll()
}

Delete All Realm Objects During Runtime

You can do this by using results- For instance, if I want to delete all Dog objects, I can do the following-

// obtain the results of a query

RealmResults<Dog> results = realm.where(Dog.class).findAll();

// All changes to data must happen in a transaction
realm.beginTransaction();

// Delete all matches
results.deleteAll();

realm.commitTransaction();

Ref: documentation

How to delete all records from realm object without fetching it in android?


realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
realm.delete(Movies.class);
}
});

In older Realm versions, it was called Realm.clear(Movies.class);.

Realm Delete an Object in One to Many relationship

The code in the question is very close to being correct, you just need to filter for the product you want to delete instead of the shop. It's not clear if you know the product _id or name but you can filter by either one.

Here's the code to filter for products with an _id of 1 and then delete it (which will also remove it from any lists that contain a reference to it.

const prod = realm.objects('Products').filtered("_id == 1");
realm.write(() => {
realm.delete(prod);
prod == null;
})

The above is taken from the documentation Filter Query and Delete An Object

Keep in mind this will delete all products with id = 1 so as long as _id's are unique it's fine.

Does Realm deleteAll() Reset Primary Keys

Realm.deleteAll() removes all objects stored in the Realm. The values of primary key properties must be unique amongst objects stored in the Realm. Deleting an object with a given primary key value allows that value to be used for a new object going forwards.



Related Topics



Leave a reply



Submit