1

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?

2
  • 1
    what is a type of "productStyle" ? Commented Oct 7, 2013 at 4:30
  • It is of type NSString but only holds number data Commented Oct 8, 2013 at 19:37

2 Answers 2

5

How about just inverting the compare order?

NSArray *sortedProductsByStyle = [unsortedProducts sortedArrayUsingComparator: ^(Product *p1, Product *p2) {
    return [p2.productStyle compare:p1.productStyle options:NSNumericSearch];
}];
Sign up to request clarification or add additional context in comments.

2 Comments

I tested it, and in this particular escenario it actually works. Let's see what happens when is not a numeric search, i think is going to work too, though. Thank you very much Gabriele!
NSNumericSearch changes the result of the compare, according to the type (which you didn't specify in your question). That said, inverting the comparison order will always invert the final result order ;)
-1

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.

7 Comments

Why should the cast help?
I think you are confused about what casting does.
1. if productStyle is an integer, the original code won't even compile. 2. Casting does not change the type of the object, it just makes the compiler believe it is a NSString, but at runtime it changes nothing.
@GabrielePetronella, i know it just consider as a string.
Adding a cast, as you propose, changes nothing if productStyle is a NSString and it's just wrong and potentially dangerous if it's not.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.