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
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
.