Sorting NSDates

2019-06-05 12:12发布

问题:

i have several dictionaries in my program,i have put all those dictionaries in an array i want to sort those dates accordingly dictionary should exchange its position,below shown is the code i am using,but i am not getting it sorted.Please help me to fix this issue

**NSLog(@"before sorting---%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);**

回答1:

Looks like you're reinventing the wheel here (sorting has been solves decades ago), do this instead:

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

or this:

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