Sort an NSArray in Descending Order

前端 未结 11 1090
死守一世寂寞
死守一世寂寞 2020-12-08 02:23

I have an NSArray of NSNumber objects that I have successfully sorted in ascending order using the following:

[myArray sortedArrayU         


        
相关标签:
11条回答
  • 2020-12-08 02:51

    If you need based on ABCD in ascending then use following code

    NSSortDescriptor *descriptor=[[NSSortDescriptor alloc] initWithKey:@"self" ascending:YES];
    NSArray *descriptors=[NSArray arrayWithObject: descriptor];
    NSArray *reverseOrder=[yourArray sortedArrayUsingDescriptors:descriptors];
    
    0 讨论(0)
  • 2020-12-08 02:52

    use sortarrayusingcomparator method like that

    NSArray *sortedArray = [array sortedArrayUsingComparator:
    ^NSComparisonResult(id obj1, id obj2){
            return [obj2 compare:obj1];
        }];
    

    by reversing the order of objects you will obtain a descending order

    0 讨论(0)
  • 2020-12-08 02:56

    There are a few ways:

    1. Write a comparison function and pass it to sortUsingFunction:context:.
    2. Use sortUsingComparator:, which takes a block. (Only available in Mac OS X 10.6 and later and iOS 4.0 and later.)
    3. Use sortUsingDescriptors:, and pass an array of at least one sort descriptor whose ascending property is false.

    In the first two cases, your comparison should simply return the negation of what the comparator you normally use (e.g., compare:) returned. The last one involves less custom code, so it's what I'd use.

    0 讨论(0)
  • 2020-12-08 02:59

    Use a sort descriptor

    NSSortDescriptor* sortOrder = [NSSortDescriptor sortDescriptorWithKey: @"self" 
                                                                ascending: NO];
    return [myArray sortedArrayUsingDescriptors: [NSArray arrayWithObject: sortOrder]];
    
    0 讨论(0)
  • 2020-12-08 03:03

    comare selector has to return NSComparisonResult. It's actually your function, so you can write another function, that returns the opposite result to sort in descending order.

    0 讨论(0)
  • 2020-12-08 03:03

    Use the following code to sort Array on the basis of key on which you want to sort tge array (e.g name , code, address,emp_id etc...)

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Enter Sort Type" ascending:NO];
    
    NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
    return [array sortedArrayUsingDescriptors:sortDescriptors];
    
    0 讨论(0)
提交回复
热议问题