Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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?

like image 735
Doug Smith Avatar asked Jul 31 '13 01:07

Doug Smith


2 Answers

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 
 }
like image 159
Mario Avatar answered Sep 19 '22 14:09

Mario


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];
}
like image 37
Lucas Eduardo Avatar answered Sep 18 '22 14:09

Lucas Eduardo