NSPredicate忽略了空格

Jia*_*Yow 7 whitespace cocoa-touch objective-c nspredicate

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

谓词看起来像这样:

[NSPredicate predicateWithFormat:@"Key ==[cdw] %@", userInputKey];
Run Code Online (Sandbox Code Playgroud)

'w'修饰符是一种发明的修饰符来表达我想要使用的内容.

我不能只修剪它,userInputKey因为数据源"Key"值也可能在它们中有空格(它们需要那些空格,我不能事先修剪它们).

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

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

这不可能这么难,可以吗?

Nic*_*ore 11

如何定义这样的东西:

+ (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;
    }];
}
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它:

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);
Run Code Online (Sandbox Code Playgroud)

结果是:

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