如何在iPhone中以降序对数组进行sorting

我想按降序对数组进行sorting,我可以按升序对数组进行sorting,这里是我的代码按升序sorting,

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"year" ascending:NO]; NSArray * descriptors = [NSArray arrayWithObjects:sortDescriptor, nil]; sortedArray = [array sortedArrayUsingDescriptors:descriptors]; dictionaryWithSortedYears = [[NSMutableDictionary alloc] init]; NSString *tempDateKey = nil; for (TreeXmlDetails *list in sortedArray) { id obj = [dictionaryWithSortedYears objectForKey:list.year]; if(!obj) { if(tempDateKey == nil) { arrayFromList = [[NSMutableArray alloc] init]; tempDateKey = list.year; } } if([list.year isEqualToString:tempDateKey]) [arrayFromList addObject:list]; else { [dictionaryWithSortedYears setObject:arrayFromList forKey:tempDateKey]; tempDateKey = nil; arrayFromList = nil; arrayFromList = [[NSMutableArray alloc] init]; tempDateKey = list.year; [arrayFromList addObject:list]; } } [dictionaryWithSortedYears setObject:arrayFromList forKey:tempDateKey]; NSArray *arr = [dictionaryWithSortedYears allKeys]; sortedKeys = [[NSArray alloc] initWithArray:[arr sortedArrayUsingSelector:@selector(compare:)]]; 

但是,我想sorting降序数组,请帮助我。 感谢advnace。

从文档:

NSSortDescriptor的实例通过指定用于比较对象的属性,用于比较属性的方法以及比较是升序还是降序来描述sorting对象的基础。 NSSortDescriptor的实例是不可变的。

您可以通过指定要比较的属性的键path, sorting顺序(升序或降序)和(可选)用于执行比较的select器构造NSSortDescriptor的实例。

构造函数: initWithKey:升序:

返回使用给定属性键path和sorting顺序以及默认比较select器初始化的NSSortDescriptor对象。 – (id)initWithKey:(NSString *)keyPath升序:(BOOL)升序

指定顺序的参数:

如果接收方指定升序sorting,则为是,否则为否。

这些苹果文档指导您如何对数组进行sorting:

https://developer.apple.com/library/ios/documentation/cocoa/Conceptual/SortDescriptors/Articles/Creating.html

使用以下内容:

 [yourArrayToBeSorted sortUsingComparator:^NSComparisonResult(id obj1, id obj2){ return [(NSDate *)obj2 compare:(NSDate *)obj1];} ];