目标c-NSP使用自定义参数重新计算崩溃



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

这项工作非常完美:

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

但是这次崩溃出现了错误"'无法解析格式字符串"%K%@[cd]%@"'":

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

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

问题是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];

最新更新