Search code examples
iosobjective-cuisearchdisplaycontroller

How can I filter UITableView with two predicates in IOS


I have tableView with searchDisplayController. In this TV i have to arrays (first/last names) I can filter this values by names, using predicate, with this code

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self.firstName beginswith[cd]%@",searchString];
self.filteredAllClients = [AllClients filteredArrayUsingPredicate:predicate];

Can i filter this arrays using two predicates?

For example: I have names (Jack Stone, Mike Rango)

  1. If I`m entering 'J' and i should get filtered array - Jack Stone

  2. But if I'm entering 'R' and i should get filtered area - Mike Rango?


Solution

  • Yes, like this...

    NSPredicate *firstNamePredicate = [NSPredicate predicateWithFormat:@"self.firstName beginswith[cd]%@",searchString];
    NSPredicate *lastNamePredicate = [NSPredicate predicateWithFormat:@"self.lastName beginswith[cd]%@",searchString];
    
    NSPredicate *compoundPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:@[firstNamePredicate, lastNamePredicate]];
    
    self.filteredAllClients = [AllClients filteredArrayUsingPredicate:compoundPredciate];
    

    This will then show all people whose first names begin with the search OR whose last names begin with the search.

    I prefer using this format to using the ORs and ANDs in a single predicate as it makes the overall code more readable.

    This can also be used to get the NOT of a predicate.

    You can also easily get confused if you have compound predicates built in a single predicate.