han*_*Dev 4 cocoa objective-c nssortdescriptor
我正在使用以下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];
Run Code Online (Sandbox Code Playgroud)
Mon*_*olo 13
仅对数组进行排序还不够 - 您还需要对其进行过滤.
如果我们维护原始代码的结构,您可以添加如下过滤器:
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];
Run Code Online (Sandbox Code Playgroud)
如果性能成为问题,您可能想要反转过滤和排序,但这是一个细节.
| 归档时间: |
|
| 查看次数: |
15016 次 |
| 最近记录: |