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.
Yoshitaka
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.
Figured it out like this:
let sortProperties = [RLMSortDescriptor(property: "dateStart", ascending: true), RLMSortDescriptor(property: "timeStart", ascending: true)]
allShowsByDate = Show.allObjects().sortedResultsUsingDescriptors(sortProperties)
This is how to do it as of Realm 2.5
dataArray = try! Realm().objects(Book.self)
.sorted( by: [SortDescriptor(keyPath: "Author", ascending: true), SortDescriptor(keyPath: "Title", ascending: true)] )
Enkh-Amgalan Ch
Updated for Swift 4 syntax
let sortProperties = [SortDescriptor(keyPath: "queue"), SortDescriptor(keyPath: "name")]
let dogList = realm.objects(Dog.self).sorted(by: sortProperties)
i have found a solution.
var dataSource: Results<DLVCasting>! = nil
let realm = try! Realm()
let sortDescriptors = [SortDescriptor(property: "someValue", ascending: false)]
dataSource = realm.objects(MyClass.self).sorted(sortDescriptors);
dataSource = dataSource.sorted("anotherValue", ascending: false)
But if you put more than one sort descripton in array like example below
let sortDescriptors = [SortDescriptor(property: "someValue", ascending: false),SortDescriptor(property: "someValue", ascending: false)]
this won't work. I really don't understand why.
来源:https://stackoverflow.com/questions/27365809/order-by-multiple-properties-using-realm