0

I have a NSMutableDictionary, that contains contact names (NSString's) and the dates (NSDate's). The names are the keys. How do I sort the names by date created?

I assume I have to create a NSMutableArray of the dates, then sort it somehow. But then how do I get the names for the dates? How do I even sort NSDate's?

Thanks!

Dinesh Raja
  • 8,501
  • 5
  • 42
  • 81
Zach Lucas
  • 1,631
  • 5
  • 15
  • 29
  • Maybe this can help: http://stackoverflow.com/a/7628808/1758762 – Leo Chapiro May 15 '13 at 14:44
  • 1
    You can't sort an NSDictionary. You must copy the contents to an NSArray or some such to sort them. – Hot Licks May 15 '13 at 15:09
  • [NSDictionary keys sorted by value numerically](http://stackoverflow.com/questions/1620001/nsdictionary-keys-sorted-by-value-numerically) will provide the solution. – jscs May 15 '13 at 18:55

2 Answers2

4

Try the following code if the dict contains NSString in date format:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"your date format"];

NSArray *sortedKeys = [yourDictionary  keysSortedByValueUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2)
{
    NSDate *date1 = [dateFormatter dateFromString:obj1];
    NSDate *date2 = [dateFormatter dateFromString:obj2];
    return [date1 compare:date2];
}];

The sortedKeys will contain the sorted names.

If the dictionary contains actual NSDate objects then:

NSArray *sortedKeys = [yourDictionary  keysSortedByValueUsingComparator:^NSComparisonResult(NSDate *obj1, NSDate *obj2)
{
   return [obj1 compare:obj2];
}];
danypata
  • 9,895
  • 1
  • 31
  • 44
0

You can use [myDictionary keysSortedByValueUsingSelector:@selector(compare:)];

Levi
  • 7,313
  • 2
  • 32
  • 44