我有一个带有对象作为日期的可变数组,现在我想从数组获得最大日期..我试过这样
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);
}
执行应用程序时终止..可以任何人帮助我...提前感谢
答案 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"];
这将为您提供数组中最大的日期。
答案 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