NSPredicates,范围和SearchDisplayController

时间:2010-04-08 06:54:48

标签: iphone objective-c nspredicate uisearchdisplaycontroller

使用一些自定义对象和三个范围构建搜索:所有活动以前。使用以下代码:

- (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的方法考虑了范围,但是他们只搜索一个属性。

1 个答案:

答案 0 :(得分: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]];
}