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?

元气小坏坏 提交于 2019-12-30 04:00:10

问题


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?


回答1:


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 
 }



回答2:


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.




回答3:


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];
}



回答4:


You can also directly enumerate like this:

NSMutableDictionary *xyz=[[NSMutableDictionary alloc] init];

for (NSString* key in xyz) {
    id value = [xyz objectForKey:key];
    // do stuff
} 



This is taken from the answer provided by zneak in the question: for each loop in objective c for accessing NSMutable dictionary



来源:https://stackoverflow.com/questions/17960068/with-fast-enumeration-and-an-nsdictionary-iterating-in-the-order-of-the-keys-is

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!