我有以下包含 NSDictionary(s) 的 NSArray:
NSArray *data = [[NSArray alloc] initWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:1], @"bill", [NSNumber numberWithInt:2], @"joe", nil],
[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:3], @"bill", [NSNumber numberWithInt:4], @"joe", [NSNumber numberWithInt:5], @"jenny", nil],
[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:6], @"joe", [NSNumber numberWithInt:1], @"jenny", nil],
nil];
我想创建一个过滤的 NSArray,它只包含 NSDictionary 使用 NSPredicate 匹配多个“键”的对象。
例如:
- 过滤数组以仅包含具有键“bill”和“joe”的 NSDictionary 对象[期望的结果:新的 NSArray 将包含前两个 NSDictionary 对象]
- 过滤数组以仅包含键为“joe”和“jenny”的 NSDictionary 对象[期望结果:新的 NSArray 将包含最后两个 NSDictionary 对象]
任何人都可以解释 NSPredicate 的格式来实现这一点吗?
编辑:我可以使用以下方法实现与所需 NSPredicate 类似的结果:
NSMutableArray *filteredSet = [[NSMutableArray alloc] initWithCapacity:[data count]];
NSString *keySearch1 = [NSString stringWithString:@"bill"];
NSString *keySearch2 = [NSString stringWithString:@"joe"];
for (NSDictionary *currentDict in data){
// objectForKey will return nil if a key doesn't exists.
if ([currentDict objectForKey:keySearch1] && [currentDict objectForKey:keySearch2]){
[filteredSet addObject:currentDict];
}
}
NSLog(@"filteredSet: %@", filteredSet);
我想象 NSPredicate 如果存在会更优雅?