ios - NSPredicate 用于过滤带有 ( ' ) 字符问题的数组

标签 ios objective-c nspredicate

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

    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''' 但它仍然崩溃

这是崩溃日志

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "SELF contains[c] 'b'''"'

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

最佳答案

请尝试按如下方式过滤结果:

    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);

关于ios - NSPredicate 用于过滤带有 ( ' ) 字符问题的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37320857/

相关文章:

ios - 尝试一次执行多个动画

ios - NSPredicate Core Data iOS 中的子查询

ios - NSPredicate,executeFetchRequest 崩溃

ios - 带有滤色器的 UIWebView

ios - 视频在 xcode 模拟器上播放但不在设备上播放

ios - 在数组中查找对象的最佳方法

ios - 生成随机数但未分配 UIButton

iphone - 删除对象核心数据

ios - 向后滑动时 UINavigationController 白线故障

ios - NSPredicate 未执行