0

我有一个 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 对其进行排序,有没有办法对此进行排序?谢谢。

4

1 回答 1

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

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

于 2013-01-31T00:24:47.700 回答