Parsing and changing NSPredicate

ε祈祈猫儿з 提交于 2019-12-05 17:37:26

(This is just an idea.) Every predicate is an instance of a subclass like NSCompoundPredicate or NSComparisonPredicate. So you can check the actual class of the predicate, cast it to an object of that class and then inspect its properties. If necessary, repeat the process with sub-predicates or expressions.

The following is just an example how a simple compound predicate could be "dissected" that way. It is not the general solution that checks for all cases, but may point you into the right direction.

NSPredicate *p0 = [NSPredicate predicateWithFormat:@"foo = 'bar' AND count > 17"];

if ([p0 isKindOfClass:[NSCompoundPredicate class]]) {
    NSCompoundPredicate *p0a = (NSCompoundPredicate *)p0;
    NSCompoundPredicateType type0 = p0a.compoundPredicateType;  // NSAndPredicateType
    NSPredicate *p1 = p0a.subpredicates[0];                     // foo = 'bar'
    NSPredicate *p2 = p0a.subpredicates[1];                     // count > 17
    if ([p1 isKindOfClass:[NSComparisonPredicate class]]) {
        NSComparisonPredicate *p1a = (NSComparisonPredicate *)p1;
        NSPredicateOperatorType type1 = p1a.predicateOperatorType;  // NSEqualToPredicateOperatorType
        NSExpression *e3 = p1a.leftExpression;                  // foo, NSKeyPathExpression
        NSExpression *e4 = p1a.rightExpression;                 // "bar", NSConstantValueExpression
    }
    if ([p2 isKindOfClass:[NSComparisonPredicate class]]) {
        NSComparisonPredicate *p2a = (NSComparisonPredicate *)p2;
        NSPredicateOperatorType type2 = p2a.predicateOperatorType;  // NSGreaterThanPredicateOperatorType
        NSExpression *e5 = p2a.leftExpression;                  // count, NSKeyPathExpression
        NSExpression *e6 = p2a.rightExpression;                 // 17, NSConstantValueExpression
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!