您可以构建一个自定义谓词来否定您已有的谓词。实际上,您正在获取一个现有谓词并将其包装在另一个类似于 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];
不过,我不保证它的效率,最好将可能从最终数组中删除最多字符串的字符放在第一位,以便过滤器可以短路尽可能多的比较。