你可以構建一個自定義謂詞來否定你已有的謂詞。實際上,你正在做一個現有的斷言和工作方式類似於NOT運算符另一個謂詞包裹它:
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF contains '-'"];
NSPredicate *notPred = [NSCompoundPredicate notPredicateWithSubpredicate:pred];
[resultsArray filterUsingPredicate:pred];
的NSCompoundPredicate類支持AND,OR,和NOT謂詞的類型,所以你可以去通過,並建立一個大型複合謂詞,其中包含您不想在數組中使用的所有字符,然後對其進行過濾。嘗試是這樣的:
// Set up the arrays of bad characters and strings to be filtered
NSArray *badChars = [NSArray arrayWithObjects:@"-", @"*", @"&", nil];
NSMutableArray *strings = [[[NSArray arrayWithObjects:@"test-string", @"teststring",
@"test*string", nil] mutableCopy] autorelease];
// Build an array of predicates to filter with, then combine into one AND predicate
NSMutableArray *predArray = [[[NSMutableArray alloc]
initWithCapacity:[badChars count]] autorelease];
for(NSString *badCharString in badChars) {
NSPredicate *charPred = [NSPredicate
predicateWithFormat:@"SELF contains '%@'", badCharString];
NSPredicate *notPred = [NSCompoundPredicate notPredicateWithSubpredicate:pred];
[predArray addObject:notPred];
}
NSPredicate *pred = [NSCompoundPredicate andPredicateWithSubpredicates:predArray];
// Do the filter
[strings filterUsingPredicate:pred];
我不作任何保證,而它的效率,不過,它可能把它很可能先消除從最終陣列中最字符串中的字符是一個好主意,這樣的過濾器可以儘可能多地進行短路比較。
來源
2009-07-22 16:17:07
Tim
更改標題以更好地反映這個問題作爲問。 – 2009-07-22 16:31:08