带有数组 nspredicate 过滤的 nsdictionary



我有一个表格视图,我想用可搜索的视图进行搜索。它以前有效,但是当我添加部分时,我遇到了麻烦,因为我不得不从数组更改为字典。

所以基本上我有一个看起来像这样的 NSDictionary

{ @"districtA": array with point objects, @"districtB": array with point objects}

我需要根据数组中的点 objects.name 过滤它们。之后,我想创建一个新的nsdictionary,其中包含过滤的对象。

我尝试了至少 10 种不同的方法,但我无法弄清楚,所以我认为这是我最积极的唯一方法。这是我能想到的唯一方法,如果有更简单的方法或更合乎逻辑的方法,请告诉我。

-(void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope {
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.name BEGINSWITH[c] %@",searchText];
//create new array to fill
NSArray *arrayWithFilteredPoints = [[NSArray alloc] init];
//loop through the values and put into an rray based on the predicate
arrayWithFilteredPoints = [NSArray arrayWithObject:[[self.PointList allValues] filteredArrayUsingPredicate:predicate]];
NSMutableDictionary *dict = [@{} mutableCopy];
for (Point *point in arrayWithFilteredPoints) {
    if (![dict objectForKey:Point.district])
        dict[Point.district] = [@[] mutableCopy];
        [dict[Point.district]addObject:Point];
}
self.filteredPointList = dict;
self.filteredDistrictSectionNames = [[dict allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];}

这会导致崩溃,它当然发生在使用谓词的地方,但我不知道如何调试我应该使用什么谓词:

on 'NSInvalidArgumentException', reason: 'Can't do a substring operation with something that isn't a string (lhs = (
West ) rhs = w)'
我已经

阅读了评论,你是对的。我的代码有问题。

我更改了逻辑,添加了更多步骤(例如在不需要的情况下创建NSArray)以使解决方案清晰

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.name BEGINSWITH[c] %@",searchText];
//1. create new array to fill only the Points from the dictionary
NSArray *allPoints = [self.PointList allValues];
NSMutableArray *allPointObjects = [[NSMutableArray alloc]init];
for (NSArray *array in allPoints) {
    for (Point *point in array) {
        [allPointObjects addObject:point];
    }
}
//2. loop through allPointObjects and put into an mutablearray based on the predicate
NSArray *arrayWithFilteredPoints = [[NSArray alloc] init];
arrayWithFilteredPoints = [allPointObjects filteredArrayUsingPredicate:predicate];
NSMutableDictionary *dict = [@{} mutableCopy];
for (Point *point in arrayWithFilteredPoints) {
    if (![dict objectForKey:point.district])
        dict[point.district] = [@[] mutableCopy];
        [dict[point.district]addObject:Point];
}
self.filteredPointList = dict;
self.filteredDistrictSectionNames = [[dict allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

我想要一个过滤的ns字典,我可以将其传递回我的表视图,该表视图根据键(区域)读取字典对象

从您的描述中可以清楚地看出,[self.PointList allValues]不是 Point 对象的数组,而是 Point 对象的数组。这就是你困难的根源,包括你最初的崩溃。

您需要决定如何处理;例如,如果您只需要一个大的 Point 对象数组,则在过滤之前展平数组数组。我不能进一步建议你,因为对我来说,你想要的最终结果并不明显。

编辑 您现在已经修改了代码,我可以更清楚地看到您要做什么。您有一个字典,其值是点数组,并且您正在尝试从每个数组中过滤掉一些点。我会做的是这样做 - 即,运行键,提取每个数组,过滤它,然后将其放回原处(或者如果数组现在为空,则删除键)。但我可以看到你正在做的事情应该有效,因为你已经巧妙地将键放入点中,所以你可以从中重建字典结构。

最新更新