Realm Swift: always put nil values last in sort

后端 未结 2 950
遥遥无期
遥遥无期 2021-01-11 23:59

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(_:ascendin

相关标签:
2条回答
  • 2021-01-12 00:43

    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")
    }
    
    0 讨论(0)
  • 2021-01-12 00:49

    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.

    0 讨论(0)
提交回复
热议问题