我想要过滤一系列NSDictionaries。每个字典包含对应于字符串对象的键“tid”。我想拉出所有字典,其键“tid”的对象不等于单独数组中包含的任何字符串对象。
例如,如果我有一个名为“stringObjects”的数组和一个名为“dictionaries”的字典数组,我想用伪代码执行:
for (NSString *string in stringObjects) {
//if a dictionary in dictionaries contains a string object for it's key @"tid" which is NOT equal to *string, then put it in an array
}
我一直在尝试使用NSPredicate来做这件事,但经过几次不同的尝试,我无法得到我想要的结果。这是我最近尝试的代码(实际上似乎为数组中的每个字典创建了一个数组,除了key @“tid”的对象):
NSSet *savedThreadIds = //set of strings
NSMutableArray *filtered = [NSMutableArray array];
for (NSString *threadId in savedThreadIds) {
[filtered addObjectsFromArray:[arrayOfDictionaries filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(%K != %@)", @"tid", threadId]]];
}
感谢任何帮助。
答案 0 :(得分:0)
如果我理解你的答案,你正在寻找NSCompoundPredicate:
NSMutableArray *predicates = [[NSMutableArray alloc] init];
for (NSString *string in stringObjects) {
//Create an array of predicates
NSPredicate *pred = [NSPredicate predicateWithFormat:@"NOT (tid CONTAINS[cd] %@)",string];
[predicates addObject:pred];
}
//Create a compound predicate from predicate array, with format P1 AND P2 AND P3 etc.
NSPredicate *compoundPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:predicates];
//Filter an your array using compoundPredicate.