【问题标题】:NSPredicate for filtering array with ( ' ) character issueNSPredicate 用于过滤带有 ( ' ) 字符问题的数组
【发布时间】:2016-05-19 10:42:47
【问题描述】:

这是我用字符串过滤数组的测试。如果我的字符串不包含 (') 字符,它会很好地工作

    NSMutableArray *array = [NSMutableArray arrayWithObjects:@"Nick", @"b'en", @"Adam", @"Melissa", @"arbind", nil];

    //NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] 'b'"]; -> it work
    NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] 'b''"]; -> it crash
    NSArray *beginWithB = [array filteredArrayUsingPredicate:sPredicate];
    NSLog(@"beginwithB = %@",beginWithB);

我也尝试将我的字符串更改为 'b\'''b''' 但它仍然崩溃

这是崩溃日志

由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'无法解析格式字符串“SELF contains[c]'b'''”'

如何解决?任何帮助将不胜感激。

【问题讨论】:

  • 可能无关紧要,但 contains 听起来不适合作为结果名为 beginWith... 的谓词的候选对象
  • @Alladinian 是的,这只是我的测试,我只是从stackoverflow.com/a/25738783/5381331 复制这段代码。谢谢指正

标签: ios objective-c nspredicate


【解决方案1】:

请尝试如下过滤结果:

    NSMutableArray *array = [NSMutableArray arrayWithObjects:@"Nick", @"b'en", @"Adam", @"Melissa", @"arbind", nil];
        NSString *strToBeSearched = @"b'";

        //NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] 'b'"]; -> it work

        NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] %@",strToBeSearched]; //-> it also work

        //OR

        NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] 'b\\''"];


        NSArray *beginWithB = [array filteredArrayUsingPredicate:sPredicate];
        NSLog(@"containB = %@",beginWithB);

【讨论】:

  • @PhanVănLinh 欢迎 :-)
【解决方案2】:

试试这个

NSString *searchword = @"b";
NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] %@",searchword];

你得到输出

【讨论】:

  • 如果你想要 excat 答案使用 daskblinkknight 答案,否则试试我的答案
  • 您提供了正确的解决方案,但您向我展示的方式不是很好。因为我问的是(')字符的字符串,但在您的测试中,您的字符串不包含(')。无论如何,非常感谢你给我一个正确的解决方案;)
【解决方案3】:

当你尝试反斜杠时,你已经很接近了。这是NSPredicate 用来转义特殊字符的字符。但是,您需要两个而不是一个反斜杠:

NSMutableArray *array = [NSMutableArray arrayWithObjects:@"Nick", @"b'en", @"Adam", @"Melissa", @"arbind", nil];
NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] 'b\\''"];
//                                                                              ^^
NSArray *beginWithB = [array filteredArrayUsingPredicate:sPredicate];
NSLog(@"beginwithB = %@",beginWithB);

您需要两个的原因是 Objective-C 编译器。它处理代码中的所有字符串文字,并替换它遇到的转义序列。如果您希望 NSPredicate 看到一个反斜杠,则您的字符串文字需要有两个反斜杠,因为反斜杠本身在 Objective-C 字符串文字中被编码为 \\

【讨论】:

    【解决方案4】:

    如果你的名字是 b'en 那么,

     NSString *name = @"b'en";
     NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name == \"%@\"", name];
    

    希望这会有所帮助:)

    【讨论】:

    • 它因错误而崩溃:this class is not key value coding-compliant for the key name.'。我找到了解决方案。感谢您的帮助
    猜你喜欢
    • 2012-08-18
    • 2014-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多