0

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()
}
Hamish
  • 78,605
  • 19
  • 187
  • 280

1 Answers1

0

If you enter more than 2 characters, your program will try to access the second element of fullName, which is non-existent if you don't have a whitespace in your text.

Replace

if searchText.count > 1
else if searchText.count == 1

with

if fullName.count > 1
else if fullName.count == 1

Moreover, your code has lots of force unwrapping. You should avoid using it, especially if your data depends on user input.

Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
  • Which line causes the crash? Set up an [exception breakpoint](https://stackoverflow.com/questions/17802662/exception-breakpoint-in-xcode) if you haven't already. – Tamás Sengel Oct 05 '17 at 10:52