在目标c中从数组中查找最大日期

时间:2016-06-29 04:32:33

标签: ios objective-c

我有一个带有对象作为日期的可变数组,现在我想从数组获得最大日期..我试过这样

NSMutableArray *arrDates = [[NSMutableArray alloc]init];
NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateFormat:@"yyyy-MM-dd"];
for (int i = 0; i<dateArray2.count; i++)
{
    [arrDates addObject:[df dateFromString:dateArray2[i]]];
     }
     NSLog(@"%@",arrDates);
NSDate *maxDate=[arrDates valueForKeyPath:@"@max.date"];
NSLog(@"max date is %@",maxDate);
}

执行应用程序时终止..可以任何人帮助我...提前感谢

3 个答案:

答案 0 :(得分:3)

由于您已经在迭代输入数组,因此无需构建日期数组;只需跟踪第一个数组中的最新日期:

NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateFormat:@"yyyy-MM-dd"];
NSDate *latestDate  = [df dateFromString:dateArray2[0]];
for (int i = 1; i<dateArray2.count; i++)
{   
    NSDate *compareDate = [df dateFromString:dateArray2[i]];
    latestDate = [latestDate laterDate:compareDate];
}
NSLog(@"max date is %@",maxDate);

答案 1 :(得分:2)

你可以使用,

NSDate *maxDate = [dateArray valueForKeyPath:@"@max.self"];

这将为您提供数组中最大的日期。

了解更多https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/KeyValueCoding/Articles/CollectionOperators.html

答案 2 :(得分:1)

NSMutableArray *arrDates = [[NSMutableArray alloc]init];

NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"date"
                                             ascending:NO];

NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
arrDates = [[dateArray2 sortedArrayUsingDescriptors:sortDescriptors] mutableCopy];

NSString *maxdate=[arrDates objectatindex:0];

sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"date"
                                             ascending:NO];
此行@"date"中的

是您在数组中的key