如何最快,最简单地删除RealmResults列表中的所有项目?

时间:2016-01-27 14:53:58

标签: java android realm datastore

我有一行返回带有一些排序数据的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.

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

4 个答案:

答案 0 :(得分:3)

尝试清除方法

来自文档:

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

答案 1 :(得分:2)

要降级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();

答案 2 :(得分:2)

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

答案 3 :(得分:0)

好的,我使用的是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 {}

结果&lt;&gt;中未定义所有三种方法。数据类型。这个问题的当前答案是什么?