Reputation: 348
I'm looping through an NSDictionary that contains dictionaries named 1, 2, 3, etc. The issue I'm having is that while looping through them they do not keep a sequential order. Is there a way to maintain the numeric order while looping? thanks.
Code:
NSDictionary *theDict = [thePreviousKey objectForKey:@"stayInLine"];
for(NSString *key in theDict) {
[self doThis:key];
// expected result (do 1, 2, 3, etc.)
// actual result (1, 3, 2, etc.)
}
Plist:
<dict>
<key>randomStuff</key>
<dict>
<key>specificStuff</key>
<dict>
<key>stayInLine</key>
<dict>
<key>1</key>
<dict>
<key>thing</key>
<data>
data==
</data>
</dict>
<key>2</key>
<dict>
<key>thing</key>
<data>
data==
</data>
</dict>
</dict>
</dict>
</dict>
</dict>
Upvotes: 1
Views: 381
Reputation: 21373
NSDictionary
doesn't maintain an ordered list of keys. When you enumerate the keys in the dictionary, the order in which the keys are enumerated is undefined.
The solution is to sort the keys yourself, first. Something like this:
NSArray *keys = [[theDict allKeys] sortedArrayUsingSelector:@selector(compare:)];
for (NSString *key in keys) {
[self doThis:key];
}
Upvotes: 6