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