1

I create a NSDictionary, I put there some few objects and keys. But the problem is that the keys is sorted as I understood by the first letters of the key. For example, I put "G", "B", "C". So it is sorting and displaying them as, "B", "C", "G". I would like to disable the sorting, how could I do this. I'm working with more complicated example, but I would like to keep the situation simple in my question. Question: How I could disable sorting in NSDictionary or how could I sort the NSDictionary myself?

Thanks in advance!

woz
  • 10,888
  • 3
  • 34
  • 64
Anatoliy Gatt
  • 2,501
  • 3
  • 26
  • 42
  • 2
    They aren't sorted, they're just in an arbitrary order. For all intents and purposes it's random, and it can change from one call to the next. – Hot Licks Jul 10 '12 at 19:29
  • possible duplicate of [Stop NSDictionary from sorting its items](http://stackoverflow.com/questions/9797621/stop-nsdictionary-from-sorting-its-items) – jscs Jul 10 '12 at 20:10
  • `NSDictionary` doesn't provide any sorting by default. If you're looking to sort your NSDictionary keys internally, check out [**NSDictionary with ordered keys**](http://stackoverflow.com/questions/376090/nsdictionary-with-ordered-keys). – mopsled Jul 10 '12 at 20:11

2 Answers2

4

"Sorting" is not something an NSDictionary knows about, if you want the data to be in a particular order, you should be using an NSArray instead

Dan F
  • 17,654
  • 5
  • 72
  • 110
4

As was stated by @Dan F, NSDictionary does not sort its entries. As was stated in the comment by @Hot Licks, NSDictionary puts its contents in arbitrary order. You should never assume anything about the order of entries in the dictionary. An NSArray is more appropriate for this kind of thing.

If you really want to display the contents of a dictionary in some pre-defined sort order, you can get a array of the keys ordered using the values they are associated with. The NSDictionary class has the keysSortedByValueUsingSelector: and keysSortedByValueUsingComparator: methods that support this. So if you wanted to control the display order by sorting the values into ascending order you could implement do something like this:

NSArray *orderedKeys = [myDictionary keysSortedByUsingSelector:@selector(caseInsensitiveCompare:)];
for (int i = 0; i < [sortedKeys count]; i++) {
    NSString *key = [sortedKeys objectAtIndex:i];
    NSLog(@"%@ = %@", key, [myDictionary objectForKey:key]);
}

The results should show each entry in the dictionary, sorted by the values within each entry.

Tim Dean
  • 8,253
  • 2
  • 32
  • 59