Realm Swift: always put nil values last in sort

久未见 提交于 2019-12-01 04:04:10

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

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.

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