使用NSDate对象排序NSArray的最快方法

时间:2014-02-04 06:13:09

标签: ios sorting

我有一个由NSDate个对象组成的数组。我能够成功对列表进行排序,但我的排序操作需要很长时间。在使用时间配置文件时,我能够发现sortUsingDescriptor占用更多时间。

这是我的代码:

NSDate *currentDate = [NSDate date];
dateForm= [[NSDateFormatter alloc]init];

[dateForm setDateFormat:@"dd/MM"];
NSSortDescriptor *desc = [[NSSortDescriptor alloc] initWithKey:@"eventDate" ascending:NO comparator:^NSComparisonResult(id obj1, id obj2) {

    if(!obj1 || !obj2)
    {
        return NSOrderedAscending;
    }

    NSString *todayString = [dateForm stringFromDate:currentDate];
    NSDate *compareDate = [dateForm dateFromString:todayString];
    NSString *date1String = [dateForm stringFromDate:obj1];
    NSString *date2String = [dateForm stringFromDate:obj2];
    NSDate *date1 = [dateForm dateFromString:date1String];
    NSDate *date2 = [dateForm dateFromString:date2String];

    if([date1 compare:compareDate]==NSOrderedAscending)
    {
        date1  = [date1 dateByAddingTimeInterval:365*24*60*60];
    }
    if([date2 compare:compareDate]==NSOrderedAscending)
    {
        date2  = [date2 dateByAddingTimeInterval:365*24*60*60];
    }
    return [date2 compare:date1];
}];

NSArray *tempArray;
tempArray=[self.theMainArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:desc]];

self.theMainArray=[tempArray mutableCopy];

NSLog(@"sort done");

如何更快地对其进行排序? 感谢

0 个答案:

没有答案