【问题标题】:Objective-c NSDictionary to NSMutableArray in certain orderObjective-c NSDictionary 以特定顺序转换为 NSMutableArray
【发布时间】:2016-06-08 02:34:33
【问题描述】:

所以我有这样的 NSDictionary:

NSDictionary *productionSchedule = [[[NSMutableDictionary alloc]initWithDictionary:[[areaData GetProductionScheduleData:communityDesc] objectForKey:@"Root"]] autorelease];

NSDictionary 的数据来自 API,由于 NSDictionary 不进行排序,API 中的数据顺序在 NSDictionary 中不同,所以现在我尝试放置 NSDictionary 的键放入一个 NSMutableArray 来处理排序。在我的 NSDictionary 中,我有一个名为 SortOrder 的值,我正在尝试根据此值 SortOrder 将 NSDictionary 中的数据放入 NSMutableArray 中(我有大约 389 个项目,SortOrder 从 0 到 389)我该怎么做?

我有这个屏幕截图,可以告诉你我的数据是什么样的:

我要做的是将密钥“V3C0183”放在第 82 项(在此之前将有 81 项)

我假设我将不得不像这样执行一个 foreach 循环:

NSMutableArray *prodSchedSortedKeys

for(int i = 0;i<[productionSchedule count];i++)
{

[prodSchedSortedKeys addObject: ? ];

}

我只是不知道根据排序顺序添加对象的下一步是什么......请帮助。

【问题讨论】:

  • 我在您提出的主题中看不到任何新内容。对数组进行排序已被多次询问。我建议您通过运行搜索来帮助自己。
  • 您的密钥是否也在您的value 字典中?
  • 键值也是一个 NSDictionary 并且该值有一个名为 SortOrder 的键并且有自己的值
  • 不相关但为什么“SortOrder”字符串的值而不是数字?
  • @rmaddy 在您的回答中(由于某种原因已被删除)order1 和 order2 每次都返回 nil

标签: ios objective-c


【解决方案1】:
NSDictionary *dic = //your dictionary;

NSArray<NSDictionary *> *values = dic.allValues;
[values sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
    return [obj1[@"SortOrder"] integerValue] > [obj2[@"SortOrder"] integerValue];
}];

现在 dic 已订购。

但这不是这个问题的最佳解决方案。服务器的数据应该是有序的,像“VC31083”这样的键也应该在键值对中。

Edit1:sortedArrayUsingComparator: 用于普通的数组排序,如果内容太大,性能不是很好。特别是在这个比较中,它做了加法操作:从字典中获取值,将 NSString 转换为 int,然后比较。您可以通过 Log 查看它在此类数据上花费了多少时间。

【讨论】:

    【解决方案2】:

    NSMutableDictionary/NSDictionary 不能这样做。看看例如Matt Gallaghers OrderedDictionary.

    也看看这个答案: Getting NSDictionary keys sorted by their respective values

    【讨论】:

      猜你喜欢
      • 2013-09-24
      • 2012-02-03
      • 2016-12-17
      • 1970-01-01
      • 2012-11-24
      • 2016-04-12
      • 1970-01-01
      • 2012-09-15
      • 1970-01-01
      相关资源
      最近更新 更多