Renexandro
Renexandro

Reputation: 464

How to sort NSArray of custom objects by a specific property in descending order?

How do I make this piece of code to order in descending order. This code always gives me the array in ascending order:

NSArray *sortedProductsByStyle = [unsortedProducts sortedArrayUsingComparator: ^(Product *p1, Product *p2) {
        return [p1.productStyle compare:p2.productStyle options:NSNumericSearch];
    }];

I thought that using NSOrderedDescending would work but it didn't:

NSArray *sortedProductsByStyle = [unsortedProducts sortedArrayUsingComparator: ^(Product *p1, Product *p2) {
        return [p1.productStyle compare:p2.productStyle options:NSNumericSearch | NSOrderedDescending];
    }];

Any ideas?

Upvotes: 1

Views: 598

Answers (2)

user1673099
user1673099

Reputation: 3289

Try this way...

sortedArray = [unsortedProducts sortedArrayUsingComparator:^(Product p1 , Product p2) {
            return [((NSString *)p1.productStyle) compare:((NSString *)p2.productStyle) options:NSNumericSearch];
        }];

Let me know if you have any problem.

Upvotes: -1

Gabriele Petronella
Gabriele Petronella

Reputation: 108151

How about just inverting the compare order?

NSArray *sortedProductsByStyle = [unsortedProducts sortedArrayUsingComparator: ^(Product *p1, Product *p2) {
    return [p2.productStyle compare:p1.productStyle options:NSNumericSearch];
}];

Upvotes: 5

Related Questions