如何通过param将NSArray拆分为NSDictationary

时间:2014-11-18 11:39:51

标签: ios objective-c nsarray nsdictionary

我有一个对象数组,每个对象都有一个param。例如,我有一个数组

obj0 {age: 18; name: Jack; class: 1a}
obj1 {age: 18; name: Jim; class: 1b}
obj2 {age: 19; name: John; class: 1b}
obj3 {age: 20; name: JB; class: 1c}

我需要通过param将数组拆分为NSDictionary。如果我采用param年龄,它将分为NSDictionary

Array0:  obj0 {age: 18; name: Jack; class: 1a}
         obj1 {age: 18; name: Jim; class: 1b}
Key: 18

Array1:  obj2 {age: 19; name: John; class: 1b}
Key: 19

Array2:  obj3 {age: 20; name: JB; class: 1c}
Key20

我怎么能意识到它?

2 个答案:

答案 0 :(得分:4)

伪代码:

result = new mutable dictionary
for each (object in array)
   age = object[@"age"]
   if (result[age] does not exist)
      result[age] = new mutable array
   append object to result[age]

瞧。

答案 1 :(得分:0)

基于Cyrille答案的实际Objective-C代码:

NSMutableDictionary *result = [[NSMutableDictionary alloc] init];

for(Object *e in allObjects)
{
    NSMutableArray *mutArrForAge = [result objectForKey:e.age];
    if(mutArrForAge == nil)
    {
        mutArrForAge = [[NSMutableArray alloc] init];
        [result setObject:mutArrForAge forKey:e.age];
    }
    [mutArrForAge addObject:e];
}

Voilá* 2