Will
Will

Reputation: 3044

Looping through a sorted dictionary un sorts it.

I have a dictionary that I have sorted. My problem is when I loop through it gets unsorted again.

    //sort the poiIDArray so it appears alphabetically
NSArray *sortedValues = [[self.pois allValues] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
NSMutableDictionary *orderedDictionary=[[NSMutableDictionary alloc]init];
for(NSString *valor in sortedValues){
    for(NSString *clave in [self.pois allKeys]){
        if ([valor isEqualToString:[self.pois valueForKey:clave]]) {
            [orderedDictionary setValue:valor forKey:clave];
        }
    }
}

NSLog(@"ordered dic: %@",orderedDictionary);


//loop through dic and get names. 
for(NSString *key in orderedDictionary) {

    NSLog(@"%@",key);

}

Here is my log.

2012-10-26 11:49:35.221 CPOP Test 4[1277:c07] ordered dic: {
"Badger Burgers" = 5;
"Costa Coffee" = 4;
"Spiffing Drinks" = 6;
"Vals Vegetables" = 7;
}
2012-10-26 11:49:35.221 CPOP Test 4[1277:c07] Costa Coffee
2012-10-26 11:49:35.222 CPOP Test 4[1277:c07] Spiffing Drinks
2012-10-26 11:49:35.222 CPOP Test 4[1277:c07] Badger Burgers
2012-10-26 11:49:35.222 CPOP Test 4[1277:c07] Vals Vegetables

Can anyone tell me why this is happening and how to fix it?

Upvotes: 0

Views: 83

Answers (1)

Wevah
Wevah

Reputation: 28242

Dictionaries are by definition unordered. If you need a particular order, use an array.

Upvotes: 5

Related Questions