How to sort using Realm? How to sort using Realm? swift swift

How to sort using Realm?


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.


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;@RealmClasspublic 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;    }}