【问题标题】:How to sort by date the nsmutabledictionary如何按日期排序nsmutabledictionary
【发布时间】:2013-01-14 23:46:16
【问题描述】:

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

【问题讨论】:

  • 这看起来像一个字典数组。您应该尝试粘贴实际的 JSON,或者从 lldb 打印此结构的实际输出,这样人们就可以确定了。

标签: ios json sorting nsmutabledictionary


【解决方案1】:

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

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

【讨论】:

  • 我将在哪里通过 StartTime?
  • 只需获取关键值并进行自己的比较。希望对您有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-19
  • 1970-01-01
  • 1970-01-01
  • 2021-09-18
相关资源
最近更新 更多