我正在使用以下 NSSortDescriptor 代码对数组进行排序。我目前按价格排序,但也想限制价格。是否可以按价格排序但只显示小于 100 的价格?
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
initWithKey: @"price" ascending: YES];
NSMutableArray *sortedArray = (NSMutableArray *)[self.displayItems
sortedArrayUsingDescriptors: [NSArray arrayWithObject:sortDescriptor]];
[self setDisplayItems:sortedArray];
[self.tableView reloadData];
最佳答案
仅对数组进行排序是不够的 - 您还需要对其进行过滤。
如果我们保持您原始代码的结构,您可以像这样添加一个过滤器:
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];
如果性能成为问题,您可能想要反转过滤和排序,但这是一个细节。
关于objective-c - 如何使用 NSSortDescriptor 对 NSMutableArray 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15382818/