How to sort using Realm?

扶醉桌前 提交于 2019-12-05 09:40:08

问题


I don't know how to sort using Realm. My current code is.

data = realm.objects(WorkoutSet)
data = data!.sorted("date")

I want to sort date an Int from high numbers to low numbers. The docs need more information and the GitHub link throws a 404 message.


回答1:


You can add an ascending parameter to the sorted method:

data = data!.sorted("date", ascending: false)

This sorts your WorkoutSet using the date field in descending order.

Update

With Swift 3 and the latest RealmSwift version this has now changed to:

data = data!.sorted(byKeyPath: "date", ascending: false)

If you want to evaluate the sort criteria yourself you could use:

data = data!.sorted(by: { (lhsData, rhsData) -> Bool in
   return lshData.something > rhsData.something
})

But be aware that sorting your results by yourself does return an Array instead of a Realm Results object. That means there will be a performance and memory overhead, because Results is lazy and if do the sorting with the above method you will lose that lazy behavior because Realm has to evaluate each object! You should stick to Results whenever possible. Only use the above method if there really is no other way to sort your items.




回答2:


Using Sort.ASCENDING or Sort.DESCENDING

import java.util.Date;

import io.realm.RealmModel;
import io.realm.annotations.Index;
import io.realm.annotations.PrimaryKey;
import io.realm.annotations.RealmClass;
import io.realm.annotations.Required;

@RealmClass
public class Pojo implements RealmModel {
    @Index
    @Required
    @PrimaryKey
    protected Long id;
    protected Date data_field;
    protected int int_field;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }
}

import java.util.List;

import io.realm.Realm;
import io.realm.RealmQuery;
import io.realm.RealmResults;
import io.realm.Sort;

public class Dao {
    public List<Pojo> getAllById(Long id) {
        Realm realm = Realm.getDefaultInstance();
        RealmQuery<Pojo> query = realm.where(Pojo.class);
        query.equalTo("pojo_id", id);

        RealmResults<Pojo> result = query.findAll();

        result = result.sort("data_field", Sort.ASCENDING);
        result = result.sort("int_field", Sort.DESCENDING);

        //detaching it from realm (optional)
        List<Pojo> copied = realm.copyFromRealm(result);

        realm.close();

        return copied;
    }
}


来源:https://stackoverflow.com/questions/34283405/how-to-sort-using-realm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!