重新安排NSArray和NSDictionary条目

时间:2012-10-17 15:01:38

标签: iphone objective-c ios nsarray nsdictionary

我有nsdictionary对象的数组,例如:

({"someKey" = "title";
  "name" = "someName";
 },
 {"someKey" = "title";
  "name" = "anotherName";
 }
 {"someKey" = "newTitle";
  "name" = "someName";
 }
)

请帮我按以下格式对其进行排序:

({"someKey" = "title";
  "names": (
    {"name" = "someName"},
    {"name" = "anotherName"}
  )
 },
 {"someKey" = "newTitle";
  "names": (
   {"name" = "someName"}
  )
 }
)

谢谢..

3 个答案:

答案 0 :(得分:1)

据我所知,你想从单个字典对象中选择单个对象。

NSArray *yourArray=.... /* array which contains this data: ({"someKey" = "title";
  "name" = "someName";
 },
 {"someKey" = "title";
  "name" = "anotherName";
 }
)*/
NSMutableDictionary *newDictionary=[[NSMutableDictionary alloc]init];

for(int i=0;i<[yourArray count];i++){
    [newDictionary setObject:[yourArray objectAtIndex:i] forKey:@"names"];
}

答案 1 :(得分:0)

 ({"someKey" = "title";
 "name" = "someName";
 },
   {"someKey" = "title";
  "name" = "anotherName";
 }
)

假设上面相当于

NSArray *array=[NSArray arrayWithObjects:dictionary1,dictionary2,nil];

然后实现以下结果

  (
{
 "someKey" = "title";
"names": (
 {"name" = "someName"},
{"name" = "anotherName"}
  )
 }
)

我们有:

 //Get name array 
 NSMutableArray *names=[NSMutableArray array];

 for(int i=0;i<[array count];i++)
 {
     NSDictionary *dictionary=[array objectAtIndex:i];
     [names addObject:[dictionary valueForKey:@"name"];
 }


 NSDictionary *newDictionary=[NSDictionary dictionaryWithOjbectsAndKeys:@"someKey",@"title",names,@"names",nil];

//Your final result is an array with one object ( A Dictionary )

NSArray *finalArray=[NSArray arrayWithObjects: newDictionary,nil];

答案 2 :(得分:0)

您只需要遍历当前结构并构建一个新标词,标题为唯一键:

NSEnumerator* arrayEnumerator = [myArray objectEnumerator];

NSDictionary* = dictFromArray;

NSMutableArray* titleArray = [[NSMutableArray alloc] init];
NSMutableDictionary* titleDict = [[NSMutableDictionary alloc] init];

while(dictFromArray = [arrayEnumerator nextObject])
{
    currentTitle = [dictFromArray objectForKey:@"someKey"];
    currentName = [dictFromArray objectForKey:@"name"];

    if([titles containsObject:currentTitle)
    {
    NSMutableDictionary namesArray = [titleDict objectForKey:currentTitle];
    [namesArray addObject:currentName];
    }
    else
    {
        [titles addObject:currentTitle];
        [titleDict addObject:[NSMutableArray arrayWithObject:currentName] forKey:currentTitle];
    }
}

这应该会给你一个类似的字典:

{
    title = 
    (
        someName,
        anotherName
    );

    newTitle = 
    (
        someName
    )
}

为了获得上面的确切结构,我认为这应该有效:

NSArray* titleKeys = [titleDict allKeys];

NSEnumerator* keyEnumerator = [titleKeys objectEnumerator];
NSMutableArray* finalArray = [[NSMutableArray alloc] init];
NSString* key;

while (key = [keyEnumerator nextObject])
{
    [finalArray addObject: [NSDictionary 
        dictionaryWithObjects:(key, [dictArray objectForKey:key])
        forKeys:(@"someKey", @"names")]];
}