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];
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.
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 !!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With