Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :)

like image 438
hanumanDev Avatar asked Dec 10 '25 00:12

hanumanDev


1 Answers

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

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
                                     initWithKey: @"reviews.n" ascending: YES];
like image 55
rmaddy Avatar answered Dec 11 '25 13:12

rmaddy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!