简体   繁体   中英

How to sort a NSMutableArray using NSSortDescriptor?

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

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:

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

thanks for any help on this :)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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