NSPredicate与自定义参数崩溃

时间:2014-04-30 03:25:51

标签: objective-c nspredicate

我尝试动态生成NSPredicate的字符串

这项工作非常完美:

NSPredicate * predicate = [NSPredicate predicateWithFormat:@" %K MATCHES[cd] %@", sKey, sLookForString];

但这次崩溃错误“'无法解析格式字符串”%K%@ [cd]%@“'”:

NSPredicate * predicate = [NSPredicate predicateWithFormat:@" %K %@[cd] %@", sKey, @"MATCHES", sLookForString];

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

1 个答案:

答案 0 :(得分:2)

问题是predicateWithFormat:不会让你动态地形成动词(语法很清楚)。因此,在您预先形成谓词字符串时动态地形成动词。像这样:

NSString* verb = @"MATCHES"; // or whatever the verb is to be
NSString* s = [NSString stringWithFormat: @" %%K %@[cd] %%@", verb];
NSPredicate * predicate = [NSPredicate predicateWithFormat:s, sKey, sLookForString];

或者使用NSExpressionNSComparisonPredicate(以及,如果需要,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];
相关问题