views:

211

answers:

1

Building a search with some custom objects and three scopes: All, Active, and Former. Got it working with the below code:

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

This works fine and takes scope into account. Since I wanted to search four fields at at time, this question helped me come up with the below code:

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

However it no longer takes scope into account.

I have been playing around with if statements, adding AND scope == 'Active', etc. to the end of the statement and using NSCompoundPredicates to no avail. Whenever I activate a scope, I'm not getting any matches for it.


Just a note that I've seen approaches like this one that take scope into account, however they only search inside one property.

+1  A: 

Here's about how I would do it:

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