4

我正在使用以下 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];
4

4 回答 4

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];

如果性能成为问题,您可能希望反转过滤和排序,但这是一个细节。

于 2013-03-13T10:45:56.427 回答
1

您可以先过滤指定价格范围的数组,然后对过滤后的数组进行排序并在表格视图中显示排序后的数组!!!

对于过滤,您可以使用NSPredicate& 对于排序,您可以使用相同的NSSortDescriptor

希望这对你有帮助!!!

于 2013-03-13T10:39:21.540 回答
0
NSMutableArray * weekDays = [[NSMutableArray alloc] initWithObjects:@"Sunday",@"Monday",@"Tuesday",@"Wednesday",@"Thursday",@"Friday",@"Saturday", nil];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
NSMutableArray *dictArray = [[NSMutableArray alloc] init];

for(int i = 0; i < [weekDays count]; i++)
{
    dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%i",i],@"WeekDay",[weekDays objectAtIndex:i],@"Name",nil];
    [dictArray addObject:dict];
}
NSLog(@"Before Sorting : %@",dictArray);

@try
{
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Name" ascending:NO];
    NSArray *descriptor = @[sortDescriptor];
    NSArray *sortedArray = [dictArray sortedArrayUsingDescriptors:descriptor];
    NSLog(@"After Sorting : %@",sortedArray);
}
@catch (NSException *exception)
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Sorting cant be done because of some error" message:[NSString stringWithFormat:@"%@",exception] delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
    [alert setTag:500];
    [alert show];
    [alert release];
}
于 2014-01-29T06:55:06.070 回答
0
NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:@"your key" ascending:true];
[yourarray sortUsingDescriptors:[NSArray arrayWithObject:sorter]];
[sorter release];
于 2013-03-13T10:35:30.260 回答