日期数组排序问题,iPhone sdk

时间:2011-09-26 09:50:08

标签: iphone uitableview nsmutablearray nsdate date-sorting

我有一个包含不同日期值的数组。我已经使用以下代码对日期数组进行排序,完成了它。

    combinedArr = [[NSMutableArray alloc]init];
NSInteger counts = [pbTitle count];
for (int i = 0; i < counts; i++) {

    CustomObject *customobject2 = [CustomObject customObjectWithName:
                                   [pbTitle objectAtIndex:i] andDate:[pbstartDate objectAtIndex:i]];
    [combinedArr addObject:customobject2];
}
[combinedArr sortUsingComparator:^NSComparisonResult(id obj1, id obj2)
 {
     return [[(CustomObject*)obj1 date]compare: [(CustomObject*)obj2 date]];
 }];
NSLog(@"Results: %@", combinedArr);

现在结果是在combinedArr中,我需要用当前系统时间检查每个值,并且需要加载到两个不同的数组中,并将这两个数组加载到tableView的两个部分中。我该如何实现呢?请帮我找一个解决方案。

1 个答案:

答案 0 :(得分:1)

我认为最简单,最快(更短的运行时间)解决方案是从头开始创建2个独立的数组,并分别对每个数组进行排序。

像这样:

NSDate *currentDate = [NSDate date];
NSMutableArray *pastArray = [[NSMutableArray alloc] init];
NSMutableArray *futureArray = [[NSMutableArray alloc] init];
NSInteger counts = [pbTitle count];

// Fill the arrays
for (int i = 0; i < counts; i++) {
    NSDate *customOnjectDate = [pbstartDate objectAtIndex:i];
    CustomObject *customobject2 = [CustomObject customObjectWithName:[pbTitle objectAtIndex:i] andDate:customOnjectDate];

    NSMutableArray *array = ([customOnjectDate compare:currentDate] == NSOrderedAscending ? pastArray : futureArray);
    [array addObject:customobject2];
}

// Sort the arrays
[pastArray sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
     return [[obj1 date] compare:[obj2 date]];
 }];
[futureArray sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
     return [[obj1 date] compare:[obj2 date]];
 }];

// Use the arrays
NSLog(@"pastArray: %@", pastArray);
NSLog(@"futureArray: %@", futureArray);

// Don't forget to release the arrays after you use them
[pastArray release];
[futureArray release];