Realm Swift: always put nil values last in sort

后端 未结 2 951
遥遥无期
遥遥无期 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: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.

提交回复
热议问题