31

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.

Cody Weaver
  • 4,756
  • 11
  • 33
  • 51

2 Answers2

77

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.

joern
  • 27,354
  • 7
  • 90
  • 105
  • I think we need to wrap ascending: false in {}, as sorted("date", {ascending:false}) – NgocDB Apr 17 '17 at 08:26
  • 1
    No, that's not correct. `ascending` is a simple boolean parameter. Please see my updated answer above. – joern Apr 17 '17 at 10:04
  • Ah yes, it is with Swift, as you clarified. With Realm Javascript, we need to use as I stated sorted("date", {ascending:false}) – NgocDB Apr 18 '17 at 10:07
-6

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;
    }
}
Igor Vuković
  • 742
  • 12
  • 25