NSPredicate没有解析和崩溃

时间:2014-08-20 08:36:36

标签: objective-c iphone ipad nspredicate

我正在尝试使用一种常见的方法来获取NSPredicates,这会导致解析错误。但是,如果我编写内联这样的东西:

NSPredicate *predicateTax_added = [NSPredicate predicateWithFormat:@"tax_added = %@",@"YES"];

它有效。

然而,以下不起作用:

NSPredicate *predicateTax_added = [self createPredicateWithFormateWhereKey:@"tax_added" operator:NSEqualToPredicateOperatorType value:@"YES"];

-(NSPredicate *)createPredicateWithFormateWhereKey:(NSString *)key operator:(NSPredicateOperatorType *)operatorType value:(NSString *)value
{
return [NSPredicate predicateWithFormat:@"%@ %@ %@",key, operatorType, value];
}

任何建议,谢谢。

2 个答案:

答案 0 :(得分:0)

有一个类似的谓词方法,predicateWithSubstitutionVariables

在此处查看更多信息:

https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Predicates/Articles/pCreating.html

我认为predicateWithFormat不能像你一样使用。

答案 1 :(得分:0)

行中有两个问题

[NSPredicate predicateWithFormat:@"%@ %@ %@",key, operatorType, value]
  • 要替换密钥,您必须使用%K格式代替%@
  • 无法替代predicateWithFormat中的运算符

要从变量键,值和运算符构建谓词,您必须构造 谓词编程:

-(NSPredicate *)createPredicateWithFormateWhereKey:(NSString *)key operator:(NSPredicateOperatorType)operatorType value:(NSString *)value
{
    NSExpression *left = [NSExpression expressionForKeyPath:key];
    NSExpression *right = [NSExpression expressionForConstantValue:value];
    NSPredicate *predicate = [NSComparisonPredicate
                              predicateWithLeftExpression:left
                              rightExpression:right
                              modifier:0
                              type:operatorType
                              options:0];
    return predicate;
}

另请注意NSPredicateOperatorType标量而不是对象,并且必须 因此不能作为指针传递。

相关问题