Thursday, December 8, 2011

How to Sort NSDictionary

Let's get this straight: you cannot sort NSDictionary.

Dictionary is a collection of keys and their objects without an order, therefore you cannot change that non-existing order. You can sort only array data types, since they are basically ordered lists.

There are still good news. You can get all keys from any dictionary as an array and sort them. Usually this is enough.

NSDictionary is a collection of unique keys and their related objects. You access each object using a key, so a lot depends on that you chose good keys. Name, timestamp or location might be good candidates.

If your keys are names and you want to sort the NSDictionary alphabetically:
NSArray *abcArray =
  [[self.dict allKeys]
If you want to sort objects based on something else but the key... first think, if you could redesign your dictionary by using something else as keys. Otherwise things might get complicated and slow. Even then slow is usually better than quick and buggy result.

Here's as an example how to sort dictionary of objects containing dates (which btw are not unique and thus could not be used as keys):
NSArray *timeArray =
  [[self.dict allKeys]
  sortedArrayUsingComparator:^(id a, id b)
    MyItem *aItem = [self.dict valueForKey:(NSString *)a];
    MyItem *bItem = [self.dict valueForKey:(NSString *)b];
    // Time order: newest first, oldest last
    return [];
Looks easy, but in my case I had a dictionary containing variable length arrays containing packed objects. Wanted to sort by date of the last objects, so needed two times six steps to get the dates for comparison.

Possible performance issue, but NOT going to fix it until it has proved to be too slow.

No comments:

Post a Comment