这是我通过字符串过滤数组的测试。如果我的字符串不包含 (') 字符,它会很好地工作
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/