-2

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.

user2981905
  • 1
  • 1
  • 1

2 Answers2

0

Use the following:

[yourArrayToBeSorted sortUsingComparator:^NSComparisonResult(id obj1, id obj2){
    return [(NSDate *)obj2 compare:(NSDate *)obj1];} ];
Deepak Bharati
  • 280
  • 2
  • 13
0

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

Pochi
  • 13,198
  • 2
  • 58
  • 99