维护NSMutableDictionary元素的顺序

时间:2019-09-03 09:23:18

标签: ios objective-c nsarray nsdictionary nsmutabledictionary

我正在获取以下格式的字典:

[
  {
    "position": "1",
    "name": "Jaen",
    "group": "Student",
    "Address": "Delhi"
  },
  {
    "position": "2",
    "name": "Jaen",
    "group": "Student",
    "Address": "Delhi"
  },
  {
    "position": "1",
    "name": "Jaen",
    "group": "Teacher",
    "Address": "Delhi"
  }
]

基本上,我想将它们分组在名为“ group”的键周围。我必须创建以下格式的字典以在UI中填充数据。

[
  {
    "Student": [
      {
        "position": "1",
        "name": "Jaen",
        "group": "Student",
        "Address": "Delhi"
      },
      {
        "position": "2",
        "name": "Jaen",
        "group": "Student",
        "Address": "Delhi"
      }
    ],
    "Teacher": [
      {
        "position": "1",
        "name": "Jaen",
        "group": "Teacher",
        "Address": "Delhi"
      }
    ]
  }
]

应保持小组的顺序,即学生应排在老师之前。但是,当我打印dictGroupField时,它会按顺序给出随机结果。

如何维护订单?

请在下面找到我正在使用的代码:

    @property (strong, nonatomic) NSMutableDictionary *dictGroupField;


    -(void)loadFieldData {

    _dictGroupField = [[NSMutableDictionary alloc] init];  

     NSMutableArray *arrayFields = [self getArrayFields];

          for (NSDictionary *dictT in arrayFields) {
    NSString *strGroup = [dict valueForKey:@"group"];

    if ([_dictGroupField valueForKey:strGroup] == nil) {

                    NSMutableArray *arrGroup = [[NSMutableArray alloc] init];
                    [arrGroup addObject:dict];
                    [_dictGroupField setObject:arrGroup forKey:strGroup];
                } else {
                    NSMutableArray *arrGroupExist = [_dictGroupField valueForKey:strGroup];
                    [arrGroupExist addObject:dict];
                    [_dictGroupField setObject:arrGroupExist forKey:strGroup];
                }
    }

}

1 个答案:

答案 0 :(得分:0)

您无法维持其顺序。
词典是键值关联的无序集合。查看更多Docs