如何使用NSSortDescriptor对NSMutableArray进行排序?

时间:2022-01-15 16:01:06

I'm parsing data from JSON webservice and then using the following code to sort the data by price, date, discount etc.

我正在解析JSON webservice的数据,然后使用以下代码按价格、日期、折扣等对数据进行排序。

here's the code I'm using to sort the data:

下面是我用来分类数据的代码:

-(void)priceSort:(id)sender {

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
                                     initWithKey: @"price" ascending: YES];

NSMutableArray *sortedArray = (NSMutableArray *)[self.displayItems
                                          sortedArrayUsingDescriptors: [NSArray arrayWithObject:sortDescriptor]];

[self setDisplayItems:sortedArray];

[self.tableView reloadData];


}

this works fine when I'm trying to sort by price, however when I want to sort by number of reviews I can't seem to get the code right:

当我试图按价格排序时,这个方法很有效,但是当我想按评论数量排序时,我似乎不能正确地找到代码:

for price I use:

对于价格我使用:

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
                                         initWithKey: @"price" ascending: YES];

but for reviews I want to get the "n" value. see how it's nested in the output (of the display Items mutableArray below:

但是对于评论,我想要得到n值。查看它是如何嵌套在输出(显示项mutableArray的如下:

"old_price" = 24;
        price = "9.9";
        reviews =         {
            **n = 11;**
            val = 70;
        };
        "sold_count" = 101;

thanks for any help on this :)

谢谢你的帮助。

1 个解决方案

#1


4  

To sort by the number of reviews n, your sort descriptor would be:

根据评论数量n排序,排序描述符是:

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
                                     initWithKey: @"reviews.n" ascending: YES];

#1


4  

To sort by the number of reviews n, your sort descriptor would be:

根据评论数量n排序,排序描述符是:

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
                                     initWithKey: @"reviews.n" ascending: YES];