我有一个 NSArray,数组中的每个对象都有一个 groupId 和一个名称。每个对象都是唯一的,但有许多具有相同的 groupId。有没有办法可以将数组拆开并重建它,以便将名称分组到具有相应 groubId 的单个对象中?这是数组当前的样子:
2013-03-12 20:50:05.572 appName[4102:702] the array: (
{
groupId = 1;
name = "Dan";
},
{
groupId = 1;
name = "Matt";
},
{
groupId = 2;
name = "Steve";
},
{
groupId = 2;
name = "Mike";
},
{
groupId = 3;
name = "John";
},
{
groupId = 4;
name = "Kevin";
}
)
这就是我希望它看起来的样子:
2013-03-12 20:50:05.572 appName[4102:702] the array: (
{
groupId = 1;
name1 = "Dan";
name2 = "Matt";
},
{
groupId = 2;
name1 = "Steve";
name2 = "Mike";
},
{
groupId = 3;
name = "John";
},
{
groupId = 4;
name = "Kevin";
}
)
编辑:我已经尝试过很多次但都失败了,大部分都是这样的(草率的娱乐,但给出一个想法):
int idNum = 0;
for (NSDictionary *arrObj in tempArr){
NSString *check1 = [NSString stringWithFormat:@"%@",[arrObj valueForKey:@"groupId"]];
NSString *check2 = [NSString stringWithFormat:@"%@",[[newDict valueForKey:@"groupId"]];
if (check1 == check2){
NSString *nameStr = [NSString stringWithFormat:@"name_%d",idNum];
[newDict setValue:[arrObj valueForKey:@"name"] forKey:nameStr];
}
else {
[newDict setValue:arrObj forKey:@"object"];
}
idNum++;
}