sortingNSDates

我有我的程序中的几个字典,我已经把所有这些字典在一个数组我想sorting这些date,因此字典应交换其位置,下面显示的是我使用的代码,但我没有得到它sorting。请帮助我解决这个问题

** NSLog(@“sort —%d”,[allDataArray count]);

for(int i=0;i<[allDataArray count]-1;i++){ NSString *dateStr1=[[allDataArray objectAtIndex:i]objectForKey:@"Date"]; for(int j=i+1;j<[allDataArray count];j++){ NSString *dateStr2=[[allDataArray objectAtIndex:j]objectForKey:@"Date"]; if(([(NSDate*)dateStr1 compare:(NSDate*)dateStr2]==NSOrderedAscending) ||([(NSDate*)dateStr1 compare:(NSDate*)dateStr2]==NSOrderedSame)) [allDataArray replaceObjectAtIndex:i withObject:[allDataArray objectAtIndex:j]]; } } NSLog(@"afterSorting-numbers--%@",allDataArray);** 

看起来你在这里重新发明轮子(sorting已经解决了几十年前),而不是这样做:

 NSArray *allDataArray = ...; NSArray *sortedAllDataArray = [allDataArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"Date" ascending:YES]]]; 

或这个:

 NSArray *allDataArray = ...; NSArray *sortedAllDataArray = [allDataArray sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *dict1, NSDictionary *dict2) { return [[dict1 objectForKey:@"Date"] compare:[dict2 objectForKey:@"Date"]]; }]