我怎样才能最快最简单地删除 RealmResults 列表中的所有项目?

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

我有一行 returns 带有一些排序数据的 RealmResult。

我想以最快最简单的方式删除所有这些项目。例如:

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

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

但是我必须使用迭代器等等,但是当我尝试这样做时,我得到了这个错误:

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

如果不是应该使用的迭代器,那么我可以使用什么?

试试清除方法

来自文档:

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();

要删除 realmResults 中的所有对象,请执行以下操作:

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

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

要迭代,您可以这样做:

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

clear() 已弃用。你应该使用 deleteAllFromRealm().

删除查询结果:

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();
    }
});

从 Realm 数据库中删除所有对象:

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

好的,我使用的是 Realm 2.8.3,代码如下:

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

所有这三种方法都没有在 Results<> 数据类型上定义。这个问题的当前答案是什么?