4

使用一些自定义对象和三个范围构建搜索:AllActiveFormer。让它使用以下代码:

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString *)scope {
    [[self filteredArtists] removeAllObjects];
    for (HPArtist *artist in [self artistList]) {
       if ([scope isEqualToString:@"All"] || [[artist status] isEqualToString:scope]) {
           NSComparisonResult result = [[artist displayName] compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])];
           if (result == NSOrderedSame) {
               [[self filteredArtists] addObject:artist];
           }
       }
    }
}

这工作正常并考虑scope在内。由于我想一次搜索四个字段,所以这个问题帮助我想出了以下代码:

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString *)scope {
    [[self filteredArtists] removeAllObjects];
    NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"familyName CONTAINS[cd] %@ OR familyKanji CONTAINS[cd] %@ OR givenName CONTAINS[cd] %@ OR givenKanji CONTAINS[cd] %@", searchText, searchText, searchText, searchText];
    [[self filteredArtists] addObjectsFromArray:[[self artistList] filteredArrayUsingPredicate:resultPredicate]];
}

但是,它不再考虑范围。

我一直在玩弄if语句,在语句的末尾添加AND scope == 'Active'等,NSCompoundPredicates但无济于事。每当我激活一个范围时,我都没有得到任何匹配项。


请注意,我已经看到像这种考虑范围的方法,但是它们只在一个属性内搜索。

4

1 回答 1

4

这是关于我将如何做到的:

NSPredicate * template = [NSPredicate predicateWithFormat:@"familyName CONTAINS[cd] $SEARCH "
                          @"OR familyKanji CONTAINS[cd] $SEARCH "
                          @"OR givenName CONTAINS[cd] $SEARCH "
                          @"OR givenKanji CONTAINS[cd] $SEARCH"];

- (void)filterContentForSearchText:(NSString *)search scope:(NSString *)scope {
  NSPredicate * actual = [template predicateWithSubstitutionVariables:[NSDictionary dictionaryWithObject:search forKey:@"SEARCH"]];
  if ([scope isEqual:@"All"] == NO) {
    NSPredicate * scopePredicate = [NSPredicate predicateWithFormat:@"scope == %@", scope];
    actual = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObjects:actual, scopePredicate, nil]];
  }

  [[self filteredArtists] setArray:[[self artistList] filteredArrayUsingPredicate:actual]];
}
于 2010-04-10T23:06:40.317 回答