4

Construire une recherche avec des objets personnalisés et trois champs d'application: Tous , active et Ancien. Got it travailler avec le code ci-dessous:NSPredicates, champs d'application et 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]; 
      } 
     } 
    } 
} 

Cela fonctionne bien et prend scope en compte. Depuis que je voulais chercher quatre champs à au moment, this question m'a aidé à venir avec le code ci-dessous:

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

Cependant, il ne prend plus en compte la portée.

J'ai joué avec if instructions, en ajoutant AND scope == 'Active', etc. à la fin de la déclaration et en utilisant NSCompoundPredicates en vain. Chaque fois que j'active une portée, je ne reçois aucun résultat.


Juste une remarque que je l'ai vu comme des approches this one qui prennent en compte la portée, mais ils recherche seulement à l'intérieur d'une propriété.

Répondre

4

Voici comment je le ferais:

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