Realm Swift: always put nil values last in sort

空扰寡人 提交于 2019-12-19 06:17:29

问题


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.


回答1:


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")
}



回答2:


In my case, multiple queries would have been difficult because in most cases my data source already does that with other sorting priorities and I only need this custom nil sorting in one circumstance. It's also very possible for there to be hundreds or thousands of results, which I would rather not keep in memory by concatenating results.

So while this is not ideal, I chose to store a hasStartDate: Bool property which is updated automatically by a computed property date: Date? with a custom setter that updates the stored startDate: Date? and hasStartDate properties. hasStartDate is also set in my initializers for the object.

This allows me to use:

realm.objects(SMItem.self).filter(predicate).sorted(by: [
    SortDescriptor(keyPath: "hasStartDate", ascending: false),
    SortDescriptor(keyPath: "startDate", ascending: true)
])

This returns objects with a startDate ascending, followed by objects without a startDate.



来源:https://stackoverflow.com/questions/37374068/realm-swift-always-put-nil-values-last-in-sort

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