When I try to enter more than 2 characters in the searchbar, the app crashes. Tried changing the logic but no use. The problem might be with the whitespaces. Here is my sample code:
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText.isEmpty {
tableViewAdapter.fetchRequestPredicate = nil
}
else {
var fullName = searchText.components(separatedBy: NSCharacterSet.whitespaces)
for (index, name) in fullName.enumerated() {
if name.isEmpty {
fullName.remove(at: index)
}
}
if searchText.count > 1 {
let firstName = fullName.first
let lastName = fullName[1]
tableViewAdapter.fetchRequestPredicate = NSPredicate(format: "firstName BEGINSWITH[cd] %@ AND lastName BEGINSWITH[cd] %@", firstName!, lastName)
}
else if searchText.count == 1 {
let firstName = fullName.first
tableViewAdapter.fetchRequestPredicate = NSPredicate(format: "firstName CONTAINS[cd] %@ AND firstName BEGINSWITH[cd] %@ OR lastName BEGINSWITH[cd] %@", firstName!, firstName!, firstName!)
}
}
tableView.reloadData()
}