【问题标题】:Maintain order of elements of NSMutableDictionary [duplicate]维护 NSMutableDictionary 元素的顺序 [重复]
【发布时间】:2020-01-06 04:27:39
【问题描述】:

我得到了以下格式的字典:

[
  {
    "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];
                }
    }

}

【问题讨论】:

  • 字典根据定义是无序的。您可以使用具有group 属性的数组和自定义类,然后您可以按组对数组进行排序。并且不要使用valueForKey,除非你知道 KVC 是什么并且你真的需要 KVC。
  • 您显示的格式不是字典它的字典数组。

标签: ios objective-c nsarray nsdictionary nsmutabledictionary


【解决方案1】:

你无法维持它的秩序。
字典是键值关联的无序集合。查看更多Docs

【讨论】:

  • 问题是我怎样才能维持秩序? 不是字典是有序的吗?
  • @Erumaru 你不能。字典是键值关联的无序集合。查看更多docs.swift.org/swift-book/LanguageGuide/CollectionTypes.html
  • 我认为你不应该向我解释。最好将其添加到您的答案中。
  • 这不能回答问题。既定的解决方案(对于这个被问得很多的问题)是在字典旁边维护一个数组。
  • 我正在寻求解决方案。我知道字典是无序的,我不能在这种情况下使用。
猜你喜欢
  • 2015-09-12
  • 2013-10-10
  • 1970-01-01
  • 2015-10-24
  • 2018-06-16
  • 2011-02-27
  • 1970-01-01
  • 2013-08-08
  • 2015-04-28
相关资源
最近更新 更多