Looping through an dictionary; why do I not get the keys alphabetically?
I am writing an iPhone app using S7Graphview and I have saved some dates and results to a .plist as keys and values in a dictionary, both as strings. My plist looks like this:
<dict>
<key>2011-05-11</key>
<string>23</string>
<key>2011-05-12</key>
<string>23</string>
<key>2011-05-13</key>
<string>23</string>
<key>2011-05-14</key>
<string>43</string>
<key>2011-06-14</key>
<string>43</string>
</dict>
Then I use this loop to load those values into the graphview:
NSMutableDictionary* dictionary = [[NSMutableDictionary alloc]init];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])
dictionary = [NSMutableDictionary dictionaryWithContentsOfFile:filePath];
int i = 1;
if ([dictionary count] > 0) {
for (NSString* key in dictionary){
NSString* verdiString = [dictionary objectForKey:key];
CGFloat verdi = [verdiString intValue];
NSDate *dato = [[NSDate alloc]init];
NSLog(@"key=%@ value=%@", key, [dictionary objectForKey:key]);
dato = [self stringTilDato:key];
[items.list_ addObject:[[GraphInfo alloc] initWithID:i name:verdiString value:verdi date:d开发者_运维知识库ato]];
i++;
}
}
The "stringTilDato" method converts the date string to a NSDate. The values get loaded into the items.list, but in the wrong order! The NSLog reports:
key=2011-05-14 value=43
key=2011-05-13 value=23
key=2011-05-12 value=23
key=2011-06-14 value=43
key=2011-05-11 value=23
key=2011-05-14 value=43
key=2011-05-13 value=23
key=2011-05-12 value=23
key=2011-06-14 value=43
key=2011-05-11 value=23
(Don't know why it goes through the keys twice, btw, but I dont't believe that's important). I thought the keys would be read alphabetically, or at least in the order of the plist. Why does the plist get loaded into the dictionary in this order, or is it my loading loop that is the problem?
Hope there is someone out there who can help me :)
A dictionary is not an ordered data structure. You can assume no particular order of the keys, and adding or removing a key can change the order completely. If you need an ordered data structure then use an array, or after getting all the keys sort them.
The documentation for NSDictionary says specifically:
The order of the elements in the array is not defined.
However, if you want the keys sorted in a particular order, there are at least three methods that return a sorted array of keys. Look at the NSDictionary reference page for methods starting with "keysSortedBy..."
Dictionaries do not ensure an ordered key output. If you want the keys displayed in a particular order, you will have to sort them prior to accessing their values and printing the result.
精彩评论