2

从这个 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
    }
    ]

谢谢。

4

2 回答 2

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;
}

)

于 2013-09-16T11:28:07.053 回答
1

枚举数组并为每个字典创建一个新字典,只使用您想要的键。将这些新字典添加到新数组中。

IE

// 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将包含仅包含您指定的键的字典。

于 2013-09-16T11:03:54.203 回答