Is it possible to apply a NSSortDescriptor
that investigates two (or more!) keys while fetching from Core Data?
Currently we fetch the objects and sort them in memory by investigating two values. We combine those two values with a computed property, just like in the following imagined example:
struct ObjectWithDates {
var date1: Date
var date2: Date
var dateForSorting: Date {
[date1, date2].max()
}
}
...Example usage...
NSSortDescriptor(key: "dateForSorting", ascending: false)
Is it possible to perform effectively this during the Core Data fetch? I had tried using a derived attribute upon the Core Data entity, but could not get the system to recognize the 'max' function. Is there something else to try, maybe programattically with NSExpression? Thank you!
No, it's not possible. You'll have to persist the dateForSorting
and update it as date1
and date2
are modified.
It's a popular idea though ;)
The reason you can’t is that the comparisons/predicate checks are happening “behind” Core Data, inside the opaque persistent store. The code you’re proposing would run on the application side, after the objects have been fetched and instantiated. If you can’t express the predicate in SQLite, then you won’t be able to come up with an equivalent predicate in Core Data.