【发布时间】:2012-06-14 09:19:20
【问题描述】:
我有以下包含 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 存在的话会更优雅?
【问题讨论】:
标签: objective-c cocoa nsarray nspredicate