Cocoa defines predicate classes (NSPredicate
, NSExpression
, etc.) which "provide a general means of specifying queries in Cocoa" Predicate Programming. This set of classes describes what I need but with one little short-coming : I'd like additional operators.
NSComparisonPredicate
already handles 14 operators (NSPredicateOperatorType) but I would like to add, say, temporal operators... or operators to represent things such as:
- " variable has at least n entries" (binary operator)
- " variable has value for, at most, n consecutive days" (ternary operator)
Obviously, I would need to implement these myself and the data model on which such queries are performed will have to support these operators. But, is there a way to implement it and benefit from the existing NSPredicate classes? Since operators were defined as an enum
, I doubt I can extend on that front. Or am I completely missing the boat on this?!
Having spent a lot of time playing around with NSPredicate
, I'm not sure this is the greatest idea.
Theoretically, you'd subclass NSPredicate
, create your new initializer and properties, and then override the -evaluateWithObject:substitutionVariables:
method to do your custom comparison.
Practically, it's probably a lot more difficult than that.
You might consider using FUNCTION()
instead. I wrote a blog post about FUNCTION
a while ago and how it plays with NSExpression
and therefore with NSPredicate
. Personally, I'd probably go with this, because then you could still use the +predicateWithFormat:
syntax to create the NSPredicate
. Creating a subclass to add an operator would necessarily prevent you from using the built-in parser.
来源:https://stackoverflow.com/questions/8362955/subclassing-nspredicate-to-add-operator