Search code examples
cocoapredicateuisearchdisplaycontroller

NSString *predicateFormat how to search two entities


hello there and sorry for the stupid question but i think i might be missing something simple here and can t figure it out myself.

i m trying to search a table view using the following code:

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{

    NSString *predicateFormat = @"(name contains[c] %@) OR (age contains[c] %@)";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateFormat, searchString];
    self.fetchedResultsController = [self resetFetchedResultsController:predicate cached:NO];

    NSError *error = nil;
    [self.fetchedResultsController performFetch:&error];

    // Return YES to cause the search result table view to be reloaded.
    return YES;
}

what i want to achieve is when the user searches the table to be able to search not only by "name" but with "age" as well!

my code above only searches the "name"

Am i missing something simple?

thank you for your time


Solution

  • Instead of:

    NSString *predicateFormat = @"(name contains[c] %@) OR (age contains[c] %@)";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateFormat, searchString];
    

    You have three options:

    NSString *predicateFormat = @"(name contains[c] %@) OR (age contains[c] %@)";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateFormat, searchString, searchString];
    

    Or:

    NSString *predicateFormat = @"(name contains[c] %1$@) OR (age contains[c] %1$@)";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateFormat, searchString];
    

    Or:

    NSString *predicateFormat = @"(name contains[c] $SEARCH) OR (age contains[c] $SEARCH)";
    NSPredicate *template = [NSPredicate predicateWithFormat:predicateFormat];
    NSPredicate *predicate = [template predicateWithSubstitutionVariables:[NSDictionary dictionaryWithObject:searchString forKey:@"SEARCH"]];
    

    The 3rd option is nice if you're building a large predicate that has an unknown number of substitutions. The 2nd is probably the simplest in terms of not repeating yourself, but the 1st is easiest to understand.