Objective c 具有自定义参数的NSPredicate崩溃

Objective c 具有自定义参数的NSPredicate崩溃,objective-c,nspredicate,Objective C,Nspredicate,我尝试为NSPredicate动态生成一个字符串 这项工作非常完美: NSPredicate * predicate = [NSPredicate predicateWithFormat:@" %K MATCHES[cd] %@", sKey, sLookForString]; 但此崩溃出现错误“'无法分析格式字符串“%K%@[cd]%@'”: 那么,如何使用“MATCHES”动态构建字符串呢?问题在于谓词WithFormat:不允许动态地形成动词(语法对此非常清楚)。因此,在预先形成谓词字符

我尝试为NSPredicate动态生成一个字符串

这项工作非常完美:

NSPredicate * predicate = [NSPredicate predicateWithFormat:@" %K MATCHES[cd] %@", sKey, sLookForString];
但此崩溃出现错误“'无法分析格式字符串“%K%@[cd]%@'”:


那么,如何使用“MATCHES”动态构建字符串呢?

问题在于
谓词WithFormat:
不允许动态地形成动词(语法对此非常清楚)。因此,在预先形成谓词字符串时动态地形成动词。大概是这样的:

NSString* verb = @"MATCHES"; // or whatever the verb is to be
NSString* s = [NSString stringWithFormat: @" %%K %@[cd] %%@", verb];
NSPredicate * predicate = [NSPredicate predicateWithFormat:s, sKey, sLookForString];
或者使用
NSExpression
NSComparisonPredicate
(如有必要,使用
NSCompoundPredicate
)在代码中完全动态地形成谓词,而不使用格式字符串。这通常是一个更好的方法
stringWithFormat:
对于最简单的情况来说确实很方便。例如:

NSExpression* eKey = [NSExpression expressionForKeyPath:sKey];
NSExpression* eLookForString = [NSExpression expressionForConstantValue:sLookForString];
NSPredicateOperatorType operator = NSMatchesPredicateOperatorType;
NSComparisonPredicateOptions opts =
    NSCaseInsensitivePredicateOption | NSDiacriticInsensitivePredicateOption;
NSPredicate* pred = 
    [NSComparisonPredicate 
        predicateWithLeftExpression:eKey 
        rightExpression:eLookForString 
        modifier:0 
        type:operator options:opts];

使用
stringWithFormat:
组合字符串。
NSExpression* eKey = [NSExpression expressionForKeyPath:sKey];
NSExpression* eLookForString = [NSExpression expressionForConstantValue:sLookForString];
NSPredicateOperatorType operator = NSMatchesPredicateOperatorType;
NSComparisonPredicateOptions opts =
    NSCaseInsensitivePredicateOption | NSDiacriticInsensitivePredicateOption;
NSPredicate* pred = 
    [NSComparisonPredicate 
        predicateWithLeftExpression:eKey 
        rightExpression:eLookForString 
        modifier:0 
        type:operator options:opts];