如何定义这样的东西:
+ (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"
)