-2

I've created NSDictionary of sorted arrays by name organized by first letter (see results below). When I use the command allKeys for that same Dictionary, the order is not the same. I need the order the same because this NSDictionary is used in UITableview and should be alphabetical.

 - (NSDictionary*) dictionaryNames {

NSDictionary *dictionary;
NSMutableArray *objects = [[NSMutableArray alloc] init];

NSArray *letters = self.exhibitorFirstLetter;
NSArray *names = self.exhibitorName;

for (NSInteger i = 0; i < [self.exhibitorFirstLetter count]; i++)
{
    [objects addObject:[[NSMutableArray alloc] init]];
}

dictionary = [[NSDictionary alloc] initWithObjects: objects forKeys:letters];

for (NSString *name in names) { 
    NSString *firstLetter = [name substringToIndex:1];

    for (NSString *letter in letters) {  //z, b
        if ([firstLetter isEqualToString:letter]) {
            NSMutableArray *currentObjects = [dictionary objectForKey:letter];
            [currentObjects addObject:name];
        }
    }

}

    NSLog(@"%@", dictionary);
NSLog(@"%@", [dictionary allKeys]);
return dictionary;

}

 B =     (
    "Baker's Drilling",
    "Brown Drilling"
);
C =     (
    "Casper Drilling"
);
J =     (
    "J's, LLC"
);
N =     (
    "Nelson Cleaning",
    "North's Drilling"
);
T =     (
    "Tim's Trucks"
);
Z =     (
    "Zach's Main",
    "Zeb's Service",
    "Zen's"
);

}

J,
T,
B,
N,
Z,
C

)

Bachzen
  • 323
  • 2
  • 8
  • 22
  • 4
    That's because NSDictionary keys are not ordered. If you want them ordered, put them in an array. – danielbeard Mar 02 '14 at 02:34
  • possible duplicate of [Is NSDictionary key order guaranteed the same as initialized if it never changes?](http://stackoverflow.com/questions/2496430/is-nsdictionary-key-order-guaranteed-the-same-as-initialized-if-it-never-changes), [NSDictionary allKeys -- does it always return the same order?](http://stackoverflow.com/q/9575387), [NSDictionary allKeys order](http://stackoverflow.com/q/17745212) – jscs Mar 02 '14 at 03:12

2 Answers2

4

NSDictionary is not an ordered collection. There's no way to control how it orders things, and it may change completely depending on OS version, device type, and dictionary contents.

Catfish_Man
  • 41,261
  • 11
  • 67
  • 84
1

I just put the NSDictionary in sorted array:

- (NSArray*)sortAllKeys:(NSArray*)passedArray{
    NSArray* performSortOnKeys = [passedArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    return performSortOnKeys;
}
pkamb
  • 33,281
  • 23
  • 160
  • 191
Bachzen
  • 323
  • 2
  • 8
  • 22