How to sort an array in descending order in iPhone [duplicate]

我与影子孤独终老i 提交于 2019-12-13 10:39:18

问题


I am trying to sort an array in descending order,I can sort array in ascending order,Here is my code to sort in ascending order,

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:)]];

But, I want to sort an array in descending array,Please help me. Thanks in advnace.


回答1:


From the docs:

An instance of NSSortDescriptor describes a basis for ordering objects by specifying the property to use to compare the objects, the method to use to compare the properties, and whether the comparison should be ascending or descending. Instances of NSSortDescriptor are immutable.

You construct an instance of NSSortDescriptor by specifying the key path of the property to be compared, the order of the sort (ascending or descending), and (optionally) a selector to use to perform the comparison.

The constructor: initWithKey:ascending:

Returns an NSSortDescriptor object initialized with a given property key path and sort order, and with the default comparison selector. - (id)initWithKey:(NSString *)keyPath ascending:(BOOL)ascending

The parameter that specifies the order:

ascending YES if the receiver specifies sorting in ascending order, otherwise NO.

And these apple docs guide you step by step on how to sort arrays:

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




回答2:


Use the following:

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


来源:https://stackoverflow.com/questions/20628387/how-to-sort-an-array-in-descending-order-in-iphone

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