Order by multiple properties using Realm

2020-05-30 03:12发布

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.

标签: ios swift realm
5条回答
一夜七次
2楼-- · 2020-05-30 03:46

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.

查看更多
聊天终结者
3楼-- · 2020-05-30 03:48

Figured it out like this:

let sortProperties = [RLMSortDescriptor(property: "dateStart", ascending: true), RLMSortDescriptor(property: "timeStart", ascending: true)]
allShowsByDate = Show.allObjects().sortedResultsUsingDescriptors(sortProperties)
查看更多
混吃等死
4楼-- · 2020-05-30 03:49

Updated for Swift 4 syntax

let sortProperties = [SortDescriptor(keyPath: "queue"), SortDescriptor(keyPath: "name")]
let dogList = realm.objects(Dog.self).sorted(by: sortProperties)
查看更多
We Are One
5楼-- · 2020-05-30 04:00

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)] )
查看更多
迷人小祖宗
6楼-- · 2020-05-30 04:01

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.

查看更多
登录 后发表回答