Sorting NSDates

坚强是说给别人听的谎言 提交于 2019-12-23 03:03:06

问题


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"]];
}]


来源:https://stackoverflow.com/questions/8136367/sorting-nsdates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!