我需要使用 NSPredicate 来匹配两个字符串,不区分大小写,不区分变音符号,和空白不敏感.
谓词看起来像这样:
[NSPredicate predicateWithFormat:@"Key ==[cdw] %@", userInputKey];
“w”修饰符是一种发明的修饰符,用于表达我想要使用的内容。
我不能只是修剪userInputKey
因为数据源“Key”值中也可能有空格(它们需要这些空格,我不能只是事先修剪它们)。
例如,给定一个userInputKey
“abc”谓词应匹配所有
{"abc", "a b c", " a B C "}
and so on. Given a
userInputKey
"a B C" the predicate should also match all the values in the set above.
这不可能很难做到,不是吗?
定义这样的东西怎么样:
+ (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"
)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)