4

建设有一些自定义的对象和三个范围搜索:所有活动。得到它与下面的代码工作:NSPredicates,范围和SearchDisplayController

- (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。因为我想在搜索四个字段的时候,this question帮我想出了下面的代码:

- (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无济于事。每当我激活一个范围,我都没有得到任何匹配。


只是我注意到我看到的方法,如this one考虑范围,但他们只在一个属性内搜索。

回答

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