如何按日期排序nsmutabledictionary

时间:2013-01-31 00:07:08

标签: ios json sorting nsmutabledictionary

我有一个JSON返回的NSMutabledictionary包含以下

  

OdometerStart = "9 miles";
    Size = 40;
    StartTime = "01-30-2013 2:30 PM";
    Tractor = T04;

  OdometerStart = "668 miles";
    Size = 40;
    StartTime = "01-30-2013 2:23 PM";
    Tractor = T04;

我需要通过StartTime对其进行排序,有没有办法对此进行排序? 感谢。

1 个答案:

答案 0 :(得分:2)

有很多方法可以进行排序。这是一个:

NSMutableDictionary *dict; //dictionary to be sorted

        NSArray *sortedKeys = [dict keysSortedByValueUsingComparator: ^(id obj1, id obj2) {
            //get the key value.
            NSString *s1 = [obj1 objectForKey:@"StartTime"];
            NSString *s2 = [obj2 objectForKey:@"StartTime"];

            //Convert NSString to NSDate:
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            //Set the AM and PM symbols
            [dateFormatter setAMSymbol:@"AM"];
            [dateFormatter setPMSymbol:@"PM"];
           //Specify only 1 M for month, 1 d for day and 1 h for hour
           [dateFormatter setDateFormat:@"M/d/yyyy h:mm:ss a"]; 
           NSDate *d1 = [dateFormatter dateFromString:s1];
           NSDate *d2 = [dateFormatter dateFromString:s2];
           [dataFormatter release];

            if ([d1 compare:d2] == NSOrderedAscending) 
                return (NSComparisonResult)NSOrderedAscending;
            if ([d1 compare:d2] == NSOrderedDescending)
                return (NSComparisonResult)NSOrderedDescending; 
            return (NSComparisonResult)NSOrderedSame;
        }];
        NSArray *sortedValues = [[dict allValues] sortedArrayUsingSelector:@selector(compare:)];

看看苹果文档: https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Collections/Articles/Dictionaries.html

在这里排序描述符apple文档: https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/SortDescriptors/Articles/Creating.html