使用快速枚举和NSDictionary,不能保证按键的顺序迭代 - 我怎样才能按顺序进行迭代? [英] With fast enumeration and an NSDictionary, iterating in the order of the keys is not guaranteed – how can I make it so it IS in order?

查看:344
本文介绍了使用快速枚举和NSDictionary,不能保证按键的顺序迭代 - 我怎样才能按顺序进行迭代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与一个API进行通信,该API将我的应用所需的数据作为响应发送回NSDictionary(数据基本上是一个提要)。这些数据按最新到最旧排序,最新项目位于NSDictionary的前面。

I'm communicating with an API that sends back an NSDictionary as a response with data my app needs (the data is basically a feed). This data is sorted by newest to oldest, with the newest items at the front of the NSDictionary.

当我用快速枚举它们时(文章中的NSString *键){...} 订单看似随机,因此我对它们进行操作的顺序不是从最新到最旧的顺序,就像我想要的那样,但是完全随机。

When I fast enumerate through them with for (NSString *key in articles) { ... } the order is seemingly random, and thus the order I operate on them isn't in order from newest to oldest, like I want it to be, but completely random instead.

我已经读过了,当使用NSDictionary的快速枚举时,不能保证按顺序迭代通过数组。

I've read up, and when using fast enumeration with NSDictionary it is not guaranteed to iterate in order through the array.

然而,我需要它。如何按NSDictionary的顺序迭代NSDictionary?

However, I need it to. How do I make it iterate through the NSDictionary in the order that NSDictionary is in?

推荐答案

一种方法是获取所有密钥在一个可变数组中:

One way could be to get all keys in a mutable array:

NSMutableArray *allKeys = [[dictionary allKeys] mutableCopy];

然后根据需要对数组进行排序:

And then sort the array to your needs:

[allKeys sortUsingComparator: ....,]; //or another sorting method

然后你可以遍历数组(使用快速枚举这里保持顺序,我认为),并获取当前密钥的字典值:

You can then iterate over the array (using fast enumeration here keeps the order, I think), and get the dictionary values for the current key:

for (NSString *key in allKeys) {
   id object = [dictionary objectForKey: key];
   //do your thing with the object 
 }

这篇关于使用快速枚举和NSDictionary,不能保证按键的顺序迭代 - 我怎样才能按顺序进行迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆