How to use NSSortDescriptor to sort an NSMutableArray

hanumanDev picture hanumanDev · Mar 13, 2013 · Viewed 15.8k times · Source

I'm using the following NSSortDescriptor code to sort an array. I'm currently sorting by price but would like to also put a limit on the price. Is it possible to sort by price but only show price less than 100 for example?

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

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

[self setDisplayItems:sortedArray];

[self.tableView reloadData];

Answer

Monolo picture Monolo · Mar 13, 2013

It is not quite enough to only sort the array - you need to filter it as well.

If we maintain the structure of your original code, you can add a filter like this:

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

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

NSPredicate *pred = [NSPredicate predicateWithFormat: @"price < 100"];
NSMutableArray *filteredAndSortedArray = [sortedArray filteredArrayUsingPredicate: pred];

[self setDisplayItems: [filteredAndSortedArray mutableCopy]];

[self.tableView reloadData];

If performance becomes an issue, you might want to inverse the filtering and the sorting, but that's a detail.