Reputation:
dictionary = (_NSDictionaryM) 3 key/value pairs
[0] = @"CELL2" : 1 : key/value pair
key = (__NSCFString) @"CELL2"
value = (__NSDictionaryM) 1 key/value pair
[0] = @"download" : @"Text Response"
key = (__NSCFString) @"download"
value = (__NSCFString) "Text Response"
[1] = @"CELL1" : 1 : key/value pair
key = (__NSCFString) @"CELL1"
value = (__NSDictionaryM) 1 key/value pair
[0] = @"download" : @"Text Response"
key = (__NSCFString) @"download"
value = (__NSCFString) "Text Response"
[2] = @"CELL3" : 1 : key/value pair
key = (__NSCFString) @"CELL3"
value = (__NSDictionaryM) 1 key/value pair
[0] = @"download" : @"Text Response"
key = (__NSCFString) @"download"
value = (__NSCFString) "Text Response"
I have a dictionary that looks like above. Using fast enumeration, I can get the "Text Responses" (which is what I ultimately want, I don't care about anything else). The issue is that I need to also get them in order when I store them into an array. The order I do get them in is consistent per dictionary (I'll always get them in 2, 1, 3,
for example), but different for each dictionary I'm going through.
Additional info:
dictionary
can have an arbitrary number of entries, but the inside of it is always the same, and I must pull the data out of a dictionary, it cannot be delivered to me in any other way.
The attempts I've tried end up with the same result I have currently (I get the text response
but out of order) or it will throw a exception because I'm performing an action on something that doesn't respond to it.
Upvotes: 1
Views: 811
Reputation: 726509
Fast enumeration pulls dictionary keys in implementation-defined order (specifically, in the order consistent with hash codes of that dictionary's keys). If you need to enforce a specific order, pull the keys out of the dictionary into NSArray
, sort that array to your liking, and then fast-iterate the array, pulling values from the dictionary for each key in the sorted order:
NSDictionary *dict = ...
// You can use any of the sortedArrayUsingXYZ methods below
NSArray *sortedKeys = [[dict allKeys] sortedArrayUsingDescriptors:...];
for (NSString *key in sortedKeys) {
id obj = [dict getObjectForKey:key];
...
}
Upvotes: 3