【问题标题】:Getting the dictionary with the most recent date from an array of dictionaries从字典数组中获取具有最新日期的字典
【发布时间】:2014-04-21 18:56:25
【问题描述】:

我有一个字典数组。这些字典的格式如下:

NSDictionary *oneDict = @{
              @"code": @"123"
              @"name": @"car"
              @"date": creationDate
}

这些字典存储在一个 NSArray 中。

我需要从该数组中提取具有最新日期的字典。

我可以通过这样做找到最近的日期:

NSArray *extractDates = [array objectForKey:@"date"];
NSArray sortedDates = [extractDates sortedArrayUsingSelector:@selector(compare:)];
NSDate *mostRecentDate = (NSDate *)[sortedDates lastObject];

现在我知道了,我可以通过数组进行交互并查找那个日期,所以我可以得到字典,但我想知道 Objective-C 是否有某种机制可以直接做到这一点。

【问题讨论】:

    标签: ios nsarray nsdate nsdictionary


    【解决方案1】:

    试试这个,

    NSSortDescriptor *dateDescriptor = [NSSortDescriptor
                                         sortDescriptorWithKey:@"date" 
                                                     ascending:YES];
    NSArray *sortDescriptors = [NSArray arrayWithObject:dateDescriptor];
    NSArray *sortedArray = [array
             sortedArrayUsingDescriptors:sortDescriptors];
    
    NSDictionary *dict = (NSDictionary *)[sortedArray lastObject];
    

    【讨论】:

    • 我认为您误读了我的问题。感谢您的代码,但是一旦我有了最近的日期,我想从具有该日期的数组中提取字典。 :)
    • 啊哈,我没有得到全貌。我以为您正在对日期数组进行排序。您正在对字典数组进行排序!!!很好。谢谢。
    猜你喜欢
    • 2020-11-06
    • 1970-01-01
    • 2022-11-27
    • 1970-01-01
    • 2014-09-19
    • 2019-07-29
    • 1970-01-01
    • 1970-01-01
    • 2019-09-21
    相关资源
    最近更新 更多