Order by multiple properties using Realm

codeman picture codeman · Dec 8, 2014 · Viewed 12k times · Source

How can I order my Realm results using multiple properties?

I'm sorting them first using one property like this:

allShows = Show.allObjects().sortedResultsUsingProperty("dateStart", ascending: true)

But now I also want to do a secondary sort by another property "timeStart". I tried like this:

allShows = Show.allObjects().sortedResultsUsingProperty("dateStart", ascending: true).sortedResultsUsingProperty("timeStart", ascending: true)

This will just make the results sorted only by the second property. Please help.

Answer

Yoshitaka picture Yoshitaka · Sep 30, 2015

In RealmSwift we can write multiple properties like this:

let sortProperties = [SortDescriptor(property: "dateStart", ascending: true), SortDescriptor(property: "timeStart", ascending: true)]
allShowsByDate = Realm().objects(MyObjectType).sorted(sortProperties)

If you want to use more properties,you can add values of SortDescriptor() to the array.