从NSDictionary的NSArray中获取什么是聪明的方法:
[
{
Key1: Value1,
Key2: Value2,
Key3: Value3,
Key4: Value4
},
{
Key1: Value11,
Key2: Value12,
Key3: Value13,
Key4: Value14
},
{
Key1: Value21,
Key2: Value22,
Key3: Value23,
Key4: Value24
}
]
NSDictionary的另一个NSArray,它包含原始密钥集的子集。例如:
[
{
Key1: Value1,
Key3: Value3
},
{
Key1: Value11,
Key3: Value13
},
{
Key1: Value21,
Key3: Value23
}
]
感谢。
答案 0 :(得分:1)
枚举数组并为每个字典,仅使用您想要的键创建一个新字典。将这些新词典添加到新数组中。
即
// Assume initialArray is the array you start with
NSMutableArray *newArray = [NSMutableArray alloc] initWithCapacity:[initialArray count]];
for (NSDictionary *dict in initialArray) {
NSDictionary *subDictionary = @{@"Key1" : [dict objectForKey:@"Key1"],
@"Key3" : [dict objectForKey:@"Key3"]};
[newArray addObject:subDictionary];
}
现在newArray
将包含仅包含您指定的键的词典。
答案 1 :(得分:1)
自由创建一个初始数组来工作......
NSArray* allKeys = @[@"key1",@"key2",@"key3",@"key4",@"key5"];
NSArray* allObjs = @[@"a",@"b",@"c",@"d",@"e"];
NSMutableArray* originalArray = [NSMutableArray arrayWithCapacity:4];
for (int i=0; i<4; i++) {
NSRange subRange = NSMakeRange(0, i+1);
[originalArray addObject:[NSDictionary dictionaryWithObjects:[allObjs subarrayWithRange:subRange] forKeys:[allKeys subarrayWithRange:subRange]]];
}
NSLog(@"origianl array = %@",originalArray);
NSArray* keys = @[@"key1",@"key3"];
__block NSMutableArray* newArr = [NSMutableArray arrayWithCapacity:4];
[originalArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[newArr addObject:[NSDictionary dictionaryWithObjects:[obj objectsForKeys:keys notFoundMarker:[NSNull null]] forKeys:keys]];
}];
NSLog(@"new array = %@",newArr);
给出了以下之前和之后:
2013-09-16 13:20:14.129 GammonPos[910:11303] origianl array = (
{
key1 = a;
},
{
key1 = a;
key2 = b;
},
{
key1 = a;
key2 = b;
key3 = c;
},
{
key1 = a;
key2 = b;
key3 = c;
key4 = d;
}
)
2013-09-16 13:20:14.131 GammonPos[910:11303] new array = (
{
key1 = a;
key3 = "<null>";
},
{
key1 = a;
key3 = "<null>";
},
{
key1 = a;
key3 = c;
},
{
key1 = a;
key3 = c;
}
)