Realm Swift:始终将nil值排在最后 [英] Realm Swift: always put nil values last in sort
问题描述
我正在用Swift 2.2编写一个针对iOS 8并使用Realm的应用程序.我允许用户使用Results.sorted(_:ascending:)
根据各种可选属性对对象进行排序.这对于降序排序非常有效,但对于升序排序,nil
值放在首位,看起来不太正确.许多数据库系统都有一个NULLS FIRST/LAST
选项,并且使用CoreData,它似乎可以
I'm writing an app in Swift 2.2 targeting iOS 8 and using Realm. I allow the user to sort objects based on various optional properties using Results.sorted(_:ascending:)
. This works very well for descending sorts but for ascending sorts, nil
values are placed first which doesn't look right. Many database systems have a NULLS FIRST/LAST
option and with CoreData, it looks like it's possible to subclass NSSortDescriptor
. Is there any way to always put nil
values last when sorting in Realm? Even if there's only a hacky strategy, that would be appreciated, too.
推荐答案
Realm不支持Results
的自定义排序,而不是Results.sorted(_:ascending:)
方法提供的功能.但是,您可以通过串联两个查询,甚至可以通过计算属性来公开该查询,从而轻松地自己完成此工作:
Realm doesn't support custom sorting of Results
other than what the Results.sorted(_:ascending:)
method gives you. But you can compose this yourself fairly easily by concatenating two queries, maybe even exposing that through a computed property:
var results: [MyModel] {
let sorted = realm.objects(MyModel).sorted("...", ascending: true)
return sorted.filter("optionalProperty != nil") +
sorted.filter("optionalProperty == nil")
}
这篇关于Realm Swift:始终将nil值排在最后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!