简体   繁体   中英

How can I delete all items in a RealmResults list fastest and easiest?

I have a line that returns a RealmResult with some sorted data.

I want to delete all these items the fastest and easiest. For example:

RealmResults<ElementEntry> currentElements = realm.where(ElementEntry.class).equalTo("type", 1).findAll();

//something like this then, would be preffered:
currentElements.removeFromRealm();

But I have to use iterators and what-not, but when I try that, I get this error:

java.util.ConcurrentModificationException: No outside changes to a Realm is allowed while iterating a RealmResults. Use iterators methods instead.

So what CAN I use, if not the very iterator that is supposed to be used?

Try the clear method

From the docs:

Removes all objects from the list. This also deletes the objects from the  underlying Realm.
@throws IllegalStateException if the corresponding Realm is closed or in an incorrect thread.

https://github.com/realm/realm-java/blob/master/realm/realm-library/src/main/java/io/realm/RealmResults.java#L636

realm.beginTransaction();
currentElements.clear()
realm.commitTransaction();

To delate all objects in a realmResults do that:

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

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

To iterate you can do that:

realm.beginTransaction();
for (int i = 0; i < results.size(); i++) {
  results.get(i).setProperty("foo");
}
realm.commitTransaction();

clear() is deprecated. You should use deleteAllFromRealm() .

Delete the results of a query:

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

realm.executeTransaction(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {
        // remove single match
        results.deleteFirstFromRealm();
        results.deleteLastFromRealm();

        // remove a single object
        Dog dog = results.get(5);
        dog.deleteFromRealm();

        // Delete all matches
        results.deleteAllFromRealm();
    }
});

Delete all objects from Realm database:

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

Okay, I am using Realm 2.8.3 and have the following code:

    do {
        let realm = try Realm()
        try realm.write {
            var results = realm.objects(Category.self)
            results.removeAll()
            results.deleteAllFromRealm()
            results.clear()
        }
    } catch {}

All three methods are not defined on the Results<> datatype. What is the current answer for this question?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM