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?

Doug Smith picture Doug Smith · Jul 31, 2013 · Viewed 24.9k times · Source

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?

Answer

Mario picture Mario · Jul 31, 2013

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 
 }