Realm-cocoa: Ordering results on multiple properties

Created on 12 Feb 2016  路  5Comments  路  Source: realm/realm-cocoa

The Sorting section of realm-swift documentation states:

"Results allows you to specify a sort criteria and order based on a single or multiple properties."

The example only shows sorting on a single property. I need to order results on multiple properties, to produce the same result as the plain old SQL: "select * from some_table order by foo, bar". Is this possible with Realm and if so what is the syntax? I've tried chaining sorted() properties to no avail.

It would be a really good idea to add an example to the documentation. Thank you!

T-Help

Most helpful comment

The section of the documentation that you mention contains links to the API documentation for Results.sorted(_:ascending:) and Results.sorted(_:). The latter takes a sequence of SortDescriptors, representing the properties to sort by. Using that could look something like:

// Sort tan dogs with names starting with "B" from oldest to youngest, then by name
let dogs = realm.objects(Dog).filter("color = 'tan' AND name BEGINSWITH 'B'")
let sortedDogs = dogs.sorted([SortDescriptor(property: "age", ascending: false), "name"])

All 5 comments

The section of the documentation that you mention contains links to the API documentation for Results.sorted(_:ascending:) and Results.sorted(_:). The latter takes a sequence of SortDescriptors, representing the properties to sort by. Using that could look something like:

// Sort tan dogs with names starting with "B" from oldest to youngest, then by name
let dogs = realm.objects(Dog).filter("color = 'tan' AND name BEGINSWITH 'B'")
let sortedDogs = dogs.sorted([SortDescriptor(property: "age", ascending: false), "name"])

Thank you @bdash that works. It wasn't clear to me when looking at the API doc. One good example does a lot to clear things up.

I agree @Alamoz that is the only useful example that I've found... 馃憤

+1

@thonydam FYI this is currently supported

Was this page helpful?
0 / 5 - 0 ratings