Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use NSSortDescriptor to sort an NSMutableArray

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];
like image 935
hanumanDev Avatar asked Dec 09 '22 17:12

hanumanDev


2 Answers

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.

like image 186
Monolo Avatar answered Dec 11 '22 09:12

Monolo


You can first filter the array with specified range in price, then sort the filtered array & display the sorted array in tableview !!!

For filtering you can use NSPredicate & for sorting you can use the same NSSortDescriptor

Hope this helps you !!!

like image 23
arun.s Avatar answered Dec 11 '22 10:12

arun.s