2

I have a NSMutableDictionary:

NSMutableDictionary = {
    "03-19" = (
            "Movie1", 
            "Movie2", 
            "Movie3"
        );
    "03-20" = (
            "Movie1"
        );
    "03-21" = (
            "Movie1", 
            "Movie2"
        );
}

Movie objects have time value. I need to sort values for every key by Movie.timeString . How should I do that?

Roo
  • 613
  • 1
  • 7
  • 24

3 Answers3

1

The value-key pairs, are in no particular order when stored in an NSDictionary or NSMutableDictionary.

You can just re-write the code by iterating through each key, and then sort, the values (stored as NSArray/NSMutableArray object, i presume) iteratively. Assuming, that it is indeed an NSMutableDictionary *dict

for(NSString *key in [dict allKeys])
{
NSArray *arrTimes = [dict objectForKey:key];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh:mm a"];

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

[dict setObject:arrSortedTimes forKey:key];
}

You may try this piece of code, and let me know, if you get any problem.

Hitesh
  • 542
  • 3
  • 12
0

Here is one option:

   NSMutableDictionary *myNewDic = [NSMutableDictionary dictionary];
   for (NSString *key in [myDictionary allKeys]) {
       [myNewDic setObject:[[myDictionary objectForKey:key] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] forKey:key];
   }

And your myNewDic is the one you need.

Asaf
  • 2,158
  • 2
  • 25
  • 40
  • And if I have NSObjects in values. And I need to sort the dictionary by time values that those objects have? – Roo Mar 30 '15 at 11:01
  • So you'll need to provide your own custom compare method. see this - http://stackoverflow.com/questions/805547/how-to-sort-an-nsmutablearray-with-custom-objects-in-it – Asaf Mar 30 '15 at 11:03
0
NSDictionary *dictionary = @{@"1": @"some value 1",
                             @"5": @"some value 5",
                             @"2" : @"some value 2"};
NSArray *sortedKeys = [dictionary keysSortedByValueUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    return [obj1 compare:obj2 options:0];
}];
NSDictionary *sorted = [NSDictionary dictionaryWithObjects:[dictionary objectsForKeys:sortedKeys notFoundMarker:@""] forKeys:sortedKeys];
Vitalii Gozhenko
  • 9,220
  • 2
  • 48
  • 66