Subclassing NSPredicate to add operator

核能气质少年 提交于 2019-12-07 05:53:50

问题


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?!


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!