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-11-30 11:42:29

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

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

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