objective-c - 忽略空格的 NSPredicate

标签 objective-c cocoa-touch whitespace nspredicate

我需要使用 NSPredicate 来匹配两个字符串,不区分大小写,不区分变音符号,和不区分空格

谓词看起来像这样:

[NSPredicate predicateWithFormat:@"Key ==[cdw] %@", userInputKey];

“w”修饰符是我发明的,用来表达我想使用的内容。

我不能只修剪 userInputKey,因为数据源“键”值中也可能有空格(它们需要那些空格,我不能预先修剪它们)。

例如,给定一个userInputKey“abc”谓词应该匹配所有

{"abc", "a b c", " a B    C   "}
等等。给定一个 userInputKey"a B C"谓词也应该匹配上面集合中的所有值。

这不会很难做到吧?

最佳答案

如何定义这样的东西:

+ (NSPredicate *)myPredicateWithKey:(NSString *)userInputKey {
    return [NSPredicate predicateWithBlock:^BOOL(NSString *evaluatedString, NSDictionary *bindings) {
        // remove all whitespace from both strings
        NSString *strippedString=[[evaluatedString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString:@""];
        NSString *strippedKey=[[userInputKey componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString:@""];
        return [strippedString caseInsensitiveCompare:strippedKey]==NSOrderedSame;
    }];
}

然后像这样使用它:

NSArray *testArray=[NSArray arrayWithObjects:@"abc", @"a bc", @"A B C", @"AB", @"a B d", @"A     bC", nil];
NSArray *filteredArray=[testArray filteredArrayUsingPredicate:[MyClass myPredicateWithKey:@"a B C"]];               
NSLog(@"filteredArray: %@", filteredArray);

结果是:

2012-04-10 13:32:11.978 Untitled 2[49613:707] filteredArray: (
    abc,
    "a bc",
    "A B C",
    "A     bC"
)

关于objective-c - 忽略空格的 NSPredicate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10088688/

相关文章:

iPhone : How to call other method from [_assetExport exportAsynchronouslyWithCompletionHandler: ^(void ) { }

css - 垂直导航栏和段落之间的空白

c++ - 如何用转义空格分割句子?

objective-c - 在 Objective C 中,如何在运行时获取 self 的类名?

objective-c - 在运行时删除框架公共(public) header

objective-c - MPMoviePlayerController 无法播放某些 3gp 格式视频

c++ - 不会用 ifstream 读取空格

iphone - 带有 UIActivityIndi​​cator 的 UIAlertView 显示得太晚/线程问题

iphone - xCode5 中新的 Core Foundation 泄漏

cocoa-touch - 为什么 NSAssert1 等而不是 NSAssert?