So *_* It 10 cocoa objective-c nsarray nspredicate
我有以下包含NSDictionary的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];
Run Code Online (Sandbox Code Playgroud)
我想创建一个过滤的NSArray,它只包含NSDictionary使用NSPredicate匹配多个"键"的对象.
例如:
任何人都可以解释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);
Run Code Online (Sandbox Code Playgroud)
我想象如果存在NSPredicate会更优雅吗?
Ale*_*Ney 24
他们唯一知道的方法是结合两个条件,如"'value1'IN列表和'value2'IN列表"
self.@ allKeys应该返回字典中的所有键(self是数组中的每个字典).如果你不用前缀@写它,那么字典只会寻找一个"allKeys"而不是方法" - (NSArray*)allKeys"
代码:
NSArray* billAndJoe = [data filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"%@ IN self.@allKeys AND %@ IN self.@allKeys" , @"bill",@"joe" ]];
NSArray* joeAndJenny = [data filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"%@ IN self.@allKeys AND %@ IN self.@allKeys" , @"joe",@"jenny" ]]
Run Code Online (Sandbox Code Playgroud)
因为nil如果你要求一个不存在的键的值,字典就会返回,所以指定该值应该是非零是足够的.以下格式应涵盖您的第一种情况:
[NSPredicate predicateWithFormat: @"%K != nil AND %K != nil", @"bill", @"joe"]
Run Code Online (Sandbox Code Playgroud)
第二种情况,"joe"和"jenny"遵循类似的模式,当然.
| 归档时间: |
|
| 查看次数: |
10784 次 |
| 最近记录: |