Order by multiple properties using Realm

南楼画角 提交于 2019-12-03 14:41:23

问题


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.


回答1:


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.




回答2:


Figured it out like this:

let sortProperties = [RLMSortDescriptor(property: "dateStart", ascending: true), RLMSortDescriptor(property: "timeStart", ascending: true)]
allShowsByDate = Show.allObjects().sortedResultsUsingDescriptors(sortProperties)



回答3:


Updated for Swift 4 syntax

let sortProperties = [SortDescriptor(keyPath: "queue"), SortDescriptor(keyPath: "name")]
let dogList = realm.objects(Dog.self).sorted(by: sortProperties)



回答4:


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)] )



回答5:


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!