对数组进行排序,它包含Date,month

时间:2014-12-15 12:13:03

标签: ios objective-c arrays sorting

我想根据日期和月份值对数组进行排序。我正在使用此代码

 NSSortDescriptor *descriptor=[[NSSortDescriptor alloc]initWithKey:@"self" ascending:YES];
    NSArray *descriptors=[NSArray arrayWithObject:descriptor];
    revereseorder=[dateAarray sortedArrayUsingDescriptors:descriptors];
    NSLog(@"date order %@",revereseorder);

我得到的反应如下:

 date order (
    "01-11-2014",
    "01-12-2014",
    "02-11-2014",
    "02-12-2014",
    "03-11-2014",
    "03-12-2014",
    "04-11-2014",
    "04-12-2014",
    "05-11-2014",
    "05-12-2014",
    "06-11-2014",
    "06-12-2014",
    "07-11-2014",
    "07-12-2014",
    "08-11-2014",
    "08-12-2014",
    "09-11-2014",
    "09-12-2014",
    "10-11-2014",
    "10-12-2014",
    "11-11-2014",
    "11-12-2014",
    "12-11-2014",
    "12-12-2014",
    "13-11-2014",
    "13-12-2014",
    "14-11-2014",
    "15-11-2014",
    "16-11-2014",
    "17-11-2014",
    "18-11-2014",
    "19-11-2014",
    "20-11-2014"

)

但是我需要根据当前月份以降序显示响应当前日期。您能否建议我如何解决?谢谢你@

3 个答案:

答案 0 :(得分:3)

如果要对字符串进行正确排序,则需要将字符串转换为实际的NSDate对象。

您可以使用比较器功能对它们进行排序......

NSArray *dateStringArray = //your array...

NSDateFormatter *dateFormatter = [NSDateFormatter new];
dateFormatter.dateFormat = @"dd-MM-yyyy";

NSArray *sortedArray = [dateStringArray sortedArrayUsingComparator:^(NSString *string1, NSString *string2) {
    NSDate *date1 = [dateFormatter dateFromString:string1];
    NSDate *date2 = [dateFormatter dateFromString:string2];

    return [date1 compare:date2];
}];

如果你想降序,那么只需将比较器的最后一行改为......

return [date2 compare:date1];

答案 1 :(得分:2)

试试这个:

NSDateFormatter *fmtdt = [[NSDateFormatter alloc] init];
[fmtdt setDateFormat:@"dd-MM-yyyy"];
NSComparator compareTimes = ^(id string1, id string2)
{
    NSDate *time1 = [fmtdt dateFromString:string1];
    NSDate *time2 = [fmtdt dateFromString:string2];
    return [time1 compare:time2];
};
NSSortDescriptor * sortDesc = [NSSortDescriptor sortDescriptorWithKey:nil ascending:YES comparator:compareTimes];
[yourArray sortUsingDescriptors:@[sortDesc]];

答案 2 :(得分:1)

NSDateFormatter是一种简单的方法,但是如果你不想使用NSDateFormatter,那么你必须通过' - '来标记每个日期。并排序,这需要更多的处理。

NSArray * token = [string componentsSeparatedByString:@" - "];