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

半世苍凉 提交于 2019-12-08 05:13:27

问题


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?


回答1:


How about just inverting the compare order?

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



回答2:


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.



来源:https://stackoverflow.com/questions/19217072/how-to-sort-nsarray-of-custom-objects-by-a-specific-property-in-descending-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!