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?

StackOverflow https://stackoverflow.com/questions/17960068

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.

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.

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

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 
 }

其他提示

Dictionaries are, by definition, unordered. If you want to apply an order to the keys, you need to sort the keys.

NSArray *keys = [articles allKeys];
NSArray *sortedKeys = [keys sortedArrayUsingSelector:@selector(compare:)];
for (NSString *key in sortedKeys) {
    // process key
}

Update the way the keys are sorted to suit your needs.

As other people said, you cannot garantee order in NSDictionary. And sometimes ordering the allKeys property it's not what you really want. If what you really want is enumerate your dict by the order your keys were inserted in your dict, you can create a new NSMutableArray property/variable to store your keys, so they will preserve its order.

Everytime you will insert a new key in the dict, insert it to in your array:

[articles addObject:someArticle forKey:@"article1"];
[self.keys addObject:@"article1"];

To enumerate them in order, just do:

for (NSString *key in self.keys) {
   id object = articles[key];
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top