我的程序中有几个词典,我把所有这些词典放在一个数组中我想对这些日期进行排序,因此字典应该交换它的位置,下面显示的是我正在使用的代码,但我没有对它进行排序。请帮我解决这个问题
** NSLog(排序前的@“ - %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);**
答案 0 :(得分:11)
看起来你在这里重新发明了轮子(排序已经解决了几十年前),而是这样做:
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"]];
}]