2012-04-10 126 views
7

我需要使用NSPredicate來匹配兩個字符串,不區分大小寫,不區分大小寫,和空白不敏感忽略空白的NSPredicate

謂詞將是這個樣子:

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

的「W」調節劑爲發明一個表達想什麼,我使用。

我不能修剪userInputKey,因爲數據源「Key」值也可能有空格(他們需要這些空格,我不能只是預先修剪它們)。

例如,給定一個userInputKey「abc」謂詞應該匹配所有的

{"abc", "a b c", " a B C "}
等等。給定一個 userInputKey「a B C」謂詞也應該匹配上面集合中的所有值。

這不能這麼難做到嗎?

回答

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; 
    }]; 
} 

然後使用它是這樣的:

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" 
) 
+0

我不得不查找HTTP://計算器.com/questions/3543208/nsfetchrequest-and-predicatewithblock因爲我想用NSFetchRequest的謂詞,但除此之外,你的解決方案n工作得很好。謝謝! – JiaYow 2012-04-10 13:20:03