过滤 NSMutableArray 并将其保存回自身

Filtering NSMutableArray and saving it back in itself

我的 uitableview 数据是从 nsmutablearray 加载的,但我也想过滤。数据加载完美,但现在我需要对其应用过滤功能并重新加载 table。到目前为止,这是我为过滤而编写的代码,但它不起作用

NSPredicate *sPredicate;
    for (int i=0; i<TableArray.count; i++) {
        float hotelDistanceFloat = [[[TableArray objectAtIndex:i]xmlhotel_distance] floatValue];
        NSInteger hotelPrice = [[[TableArray objectAtIndex:i]xmlhotel_price] integerValue];

        sPredicate = [NSPredicate predicateWithFormat:@"(%ld <= %d AND %f <= %d)" , (long)hotelPrice, numberOfBudget, hotelDistanceFloat,numberOfDistance];
        TableArray = [[TableArray filteredArrayUsingPredicate:sPredicate] mutableCopy];

    }

numberOfBudgetnumberOfDistance 是从 uislider 获取的简单 int 值。 TableArray 是我的 mutable 数组,其中包含所有 table 数据。

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return TableArray.count;
}

这些是我的 nsmutable数组包含的值

NSLog(@"Name : %@",[[TableArray objectAtIndex:1]xmlhotel_name]);
NSLog(@"City : %@",[[TableArray objectAtIndex:1]xmlhotel_city]);
NSLog(@"Price : %@",[TableArray objectAtIndex:1]xmlhotel_price);
NSLog(@"Distance : %@",[TableArray objectAtIndex:1]xmlhotel_distance);
NSLog(@"Image : %@",[[TableArray objectAtIndex:1]xmlhotel_image]);
NSLog(@"Stars : %@",[[TableArray objectAtIndex:1]xmlhotel_stars]);

所有这些值都是 STRINGS

我不确定您面临的确切问题,但这段代码看起来很可疑:

NSPredicate *sPredicate;
for (int i=0; i<TableArray.count; i++) {
    float hotelDistanceFloat = [[[TableArray objectAtIndex:i]xmlhotel_distance] floatValue];
    NSInteger hotelPrice = [[[TableArray objectAtIndex:i]xmlhotel_price] integerValue];

    sPredicate = [NSPredicate predicateWithFormat:@"(%ld <= %d AND %f <= %d)" , (long)hotelPrice, numberOfBudget, hotelDistanceFloat,numberOfDistance];
    TableArray = [[TableArray filteredArrayUsingPredicate:sPredicate] mutableCopy];
}

您应该使用包含字典的数组并将谓词中的过滤器应用于该字典。应该不需要循环来对内容进行排序。

一旦获得过滤后的数组,请重新加载 table。

你的缺点

  1. 您在枚举数组时过滤数组。
  2. 从要过滤的数组中选择谓词值。

你应该怎么做:

  1. 从输入(hotelDistanceFloat、numberOfDistance)中获取谓词的值。
  2. 像这样应用谓词:

_

NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"(hotelPrice <= %d AND numberOfBudget <= %d)" , hotelDistanceFloat,numberOfDistance];

TableArray = [[TableArray filteredArrayUsingPredicate:sPredicate].mutableCopy]

您或许可以删除 for 循环,您不需要每次都分配数组和创建谓词。

   NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"(xmlhotel_price.intValue <= %d AND xmlhotel_distance.floatValue <= %f)", numberOfBudget, numberOfDistance];
   NSMutableArray *filteredArray = [NSMutableArray arrayWithArray:[TableArray filteredArrayUsingPredicate:sPredicate]];