如何对NSDate数组进行排序(在NSMutableArray中)?

时间:2011-07-18 05:19:29

标签: sorting nsarray nsdate

任何人都可以告诉我如何对NSDate的数组(NSMutableArray)进行排序以获得实际日期吗?

谢谢!

2 个答案:

答案 0 :(得分:4)

我相信你想使用像NSMutableArray sortUsingSelector:这样的东西并传入@selector(compare:)。即,假设您NSMutableArray NSDates名为*dateArray*:

[dateArray sortUsingSelector:@selector(compare:)];

答案 1 :(得分:2)

在这里,您只需根据需求修改部分代码

- (NSArray *)sortedWeightEntriesByWeightDate:(NSArray *)unsortedArray {

    NSMutableArray *tempArray = [NSMutableArray array];
    NSMutableArray *sortedArray = [NSMutableArray arrayWithCapacity:0];

    @try {
        for(int i = 0; i < [unsortedArray count];i++) {

            NSDateFormatter *df = [[NSDateFormatter alloc]init];
            MyDataModal *entry = [unsortedArray objectAtIndex:i];       
            [df setDateFormat:@"yyyy-MM-dd"];       
            NSDate *date = [df dateFromString:entry.weightDate];        
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];

            if(date) {  
                [dict setObject:entry forKey:@"entity"];        
                [dict setObject:date forKey:@"date"];       
                [tempArray addObject:dict];
            }
            [df release];
        }

        NSInteger counter = [tempArray count];
        NSDate *compareDate;
        NSInteger index;

        for(int i = 0 ; i < counter; i++) {
            index = i;
            compareDate = [[tempArray objectAtIndex:i] valueForKey:@"date"];        
            NSDate *compareDateSecond;

            for(int j = i+1 ; j < counter; j++) {
                compareDateSecond=[[tempArray objectAtIndex:j] valueForKey:@"date"];
                NSComparisonResult result = [compareDate compare:compareDateSecond];
                if(result == NSOrderedDescending) {
                    compareDate = compareDateSecond;
                    index=j;
                }
            }
            if(i!=index)
                [tempArray exchangeObjectAtIndex:i withObjectAtIndex:index];
        }


        NSInteger counterIndex = [tempArray count];
        for(int i = 0; i < counterIndex ; i++) {
            [sortedArray addObject:[[tempArray objectAtIndex:i] valueForKey:@"entity"]];
        }

    }
    @catch (NSException * e) {
        NSLog(@"An exception occured while sorting weight entries by date");
    }
    @finally {
        return [NSArray arrayWithArray:sortedArray];
    }   
}