Jeni Khant
Jeni Khant

Reputation: 350

Scroll tableview and click in searcher crashes app

I have a tableView which is showing the list of employees. Now when I Scroll the tableView and if scroll not stopped yet and if I click the search bar, app crashes. Index out of range. I don't have any idea why this is happening. Please, if anyone can help. Thank you so much in advance.

Note: Tableview is loaded with listArray. When user search, I am searchArray to show search result.

Code:

func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
        self.searchedArray = []
        searchEnable = true
} 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{

        let cell:ListingCell = self.tableView.dequeueReusableCell(withIdentifier: "Cell") as! ListingCell

        if searchEnable {
                self.setEmployeeDetailsInTableView(cell: cell, index: indexPath.row, dataArray: searchedArray)
        }
        else{
                self.setEmployeeDetailsInTableView(cell: cell, index: indexPath.row, dataArray: listArray)
        }
}

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    if (searchBar.text?.characters.count)! > 0 {
        searchEnable = true
        getListForSearchedText(searchText)
    }
    if searchBar.text?.characters.count == 0{
        searchEnable = false
        self.tableView.reloadData()
    }
}

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
    searchEnable = false
    self.searchedArray = []
    self.tableView.reloadData()
}

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    getListForSearchedText(searchBar.text!)
    searchBar.resignFirstResponder()
}

Crash :

fatal error: Index out of range

Upvotes: 1

Views: 434

Answers (1)

Nirav D
Nirav D

Reputation: 72440

You are facing this issue because you are setting searchEnable to true too early means in the searchBarTextDidBeginEditing(_:) so that as you said tableView is still scrolling, so it will call cellForRowAtIndexPath and because of searchEnable is true you are getting this crash. Now to solved your issue you need to set searchEnable to true where you are initializing the searchedArray array and reloading the tableView.

So you need to set searchEnable to true in the method searchBar(_:shouldChangeTextIn:replacementText:) or may be inside your method getListForSearchedText.

Upvotes: 1

Related Questions