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.
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")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With