简体   繁体   English

如何按特定属性按降序对自定义对象的NSArray进行排序?

[英]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: 我认为使用NSOrderedDescending会起作用,但它没有:

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

Any ideas? 有任何想法吗?

How about just inverting the compare order? 如何反转比较顺序?

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

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. 如果您有任何问题,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM