Search code examples
iosswiftnspredicate

NSPredicate Formatting Issue


I'm creating an iOS app where I want the user to be able to search through a UITableView and display results based on a variety of different inputs. I'm using an NSPredicate with multiple conditions separated by "OR" to do this, but for some reason it's only searching with the first condition and none of the others.

Here's how my NSPredicate is formatted:

let searchPredicate = NSPredicate(format: "(SELF.firstName CONTAINS[c]
%@) OR (SELF.lastName CONTAINS[c] %@) OR (SELF.major CONTAINS[c] %@) OR
(SELF.year CONTAINS[c] %@) OR (SELF.gpa CONTAINS[c] %@)",
searchController.searchBar.text!)

My parameters are firstName, lastName, major, year, and gpa. When I type in anything besides the first name in the search bar, no results show up. But typing in a first name does indeed return matches. Why is this happening? Is my NSPredicate formatted incorrectly?


Solution

  • if let text = searchController.searchBar.text, text.characters.count > 0{
        var predicates = [NSPredicate]()
        predicates.append(NSPredicate(format: "self.firstName CONTAINS[c]",text))
        predicates.append(NSPredicate(format: "self.lastName CONTAINS[c]",text))
        predicates.append(NSPredicate(format: "self.major CONTAINS[c]",text))
        predicates.append(NSPredicate(format: "self.year CONTAINS[c]",text))
        predicates.append(NSPredicate(format: "self.gpa CONTAINS[c]",text))
    
        let searchPredicate:NSPredicate = NSCompoundPredicate(orPredicateWithSubpredicates: predicates)
    
        }