Order by multiple properties using Realm

有些话、适合烂在心里 提交于 2019-12-03 04:27:23
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.

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