Sort NSFetchRequest by a predicate
I have a SQLite-backed core data storage and would like to fetch a list of managed objects using NSFetchRequest
. I want said list to be sorted by a boolean value that can be easily calculated at the database level. I know this be开发者_开发百科cause it’s possible to formulate the same conditions using an NSPredicate
, which would look as follows:
[NSPredicate predicateWithFormat:@"uid = %@", currentUID]
Sadly, there seems to be no way to formulate a condition like this using an NSSortDescriptor
. How do I best go about this? Do I fetch two lists, one with
[NSPredicate predicateWithFormat:@"uid = %@", currentUID]
and one with
[NSPredicate predicateWithFormat:@"uid != %@", currentUID]
and combine them later on? Can I then still elegantly use a NSFetchedResultsController
?
Just create an array (even if it contains only a single element) of NSSortDescriptors
to sort the result as desired.
You use setSortDescriptors:
to set them.
The fetch can handle both predicates and sorting at the same time.
What you're asking for doesn't make sense.
A predicate is used to select which objects should be returned in a set of results. This is determined by evaluating the predicate against each object to see if the predicate evaluates to YES
or NO
(a binary value, or one of 2 possible values). If it evaluates to YES
, then the object is included. If it evaluates to NO
, then the object is excluded. There is no middle ground.
By contrast, a sort descriptor evaluates to less than
, equal
, or greater than
. In other words, it is a ternary value (it can be one of 3 things). There is no way to express a ternary value with a predicate (since a predicate is binary), and so using a predicate as a sort descriptor makes absolutely no sense. The API doesn't allow it, because logic doesn't allow it.
So the real question is: what are you trying to do? Why do you think you need a predicate in your sort descriptors?
精彩评论