【问题标题】:NSPredicate formatNSPredicate 格式
【发布时间】:2014-08-07 15:18:16
【问题描述】:

我想使用NSPredicate predicateWithFormat: 方法过滤NSArray。我有一些变量,我想以这种格式多次使用。不想多写几遍。这是一个例子:

NSString *someText = @"some text";
NSString *str = [NSString stringWithFormat:
          @"(field1 CONTAINS[cd] %1$@) OR (field2 CONTAINS[cd] %1$@)", someText];
NSLog(@"%@", str);
// prints : (field1 CONTAINS[cd] some text) OR (field2 CONTAINS[cd] some text)

所以它适用于NSString stringWithFormat:

谁能解释一下为什么它不工作 NSPredicate predicateWithFormat: 以及如何解决它?

[someArray filteredArrayUsingPredicate:
     [NSPredicate predicateWithFormat:
         @"(field1 CONTAINS[cd] %1$@) OR (field2 CONTAINS[cd] %1$@)", 
     someText]];

我收到此异常:

由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'无法解析格式字符串"(field1 CONTAINS[cd] %1$@) OR (field2 CONTAINS[cd] %1$@)"'

提前致谢

【问题讨论】:

标签: ios objective-c nsstring nspredicate


【解决方案1】:

NSPredicate 解析器不接受位置说明符,这可能是因为 $ 符号用于声明变量。顺便说一句,使用变量可以解决您的问题。

NSString *someText = @"some text";
NSPredicate *predicate = [NSPredicate predicateWithFormat:
         @"(field1 CONTAINS[cd] $someText) OR (field2 CONTAINS[cd] $someText)"]];
NSDictionary *varSub = [NSDictionary dictionaryWithObject:someText forKey:@"someText"];
NSPredicate *filterPredicate = [predicate predicateWithSubstitutionVariables:varSub];

虽然它可能不会比重新输入变量名短多少...

【讨论】:

    【解决方案2】:

    更新

    您将文字字符串作为参数传递给 -predicateWithFormat:,而不是

    [NSString stringWithFormat:@"(field1 CONTAINS[cd] %1$@) OR (field2 CONTAINS[cd] %1$@)", someText];
    

    原创

    您的-stringWithFormat: 调用提供了一个具有 2 个占位符的格式化字符串,但您只提供了一个值。

    【讨论】:

    • 正确,为什么使用 %1$@。所以它没有任何问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多