serdar aylanc
serdar aylanc

Reputation: 1347

swift - cellforrowindexpath "index out of range" error

I am getting "index out of range" error randomly in my tableview which I use for search function.

It crashes at cell.article = self.searchResults?[indexPath.row]

99% of the time it works, but sometimes even if I use the same search query it gives this error and crashes.

func updateSearchResultsForSearchController(searchController: UISearchController)
    {
        self.searchResults?.removeAll(keepCapacity: false)
        if (!searchController.searchBar.text!.isEmpty){
            let query = ["q" : searchController.searchBar.text]
            let start = 1
            let size = 15
            let index = "articles"
            let parameters : [String : AnyObject] = ["index": index, "query": String(query), "start": start, "size": size]
            let url = "http://api.url"
            Alamofire.request(.POST, url, parameters: parameters)
                .responseJSON { response in
                    guard response.result.error == nil else {
                        print(response.result.error!)
                        debugPrint(response)
                        return
                    }
                    if let value: AnyObject = response.result.value {
                        let search = JSON(value)
                        if let data = search["articles"].arrayValue as [JSON]?{
                            self.searchResults = data
                            self.view.hideLoading()
                            self.tableView.reloadData()
                        }
                    }
            }
        }
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCellWithIdentifier("SearchCell") as! SearchTableViewCell        
            let gesture = UILongPressGestureRecognizer(target: self, action: #selector(SearchTableViewController.longPressCell(_:)))
            gesture.minimumPressDuration = 0.5
            cell.addGestureRecognizer(gesture)

            cell.article = self.searchResults?[indexPath.row] ---> "EXC_BREAKPOINT" here. 
            cell.authorButton.tag = indexPath.row

            return cell
        }

Upvotes: 1

Views: 766

Answers (1)

Yury
Yury

Reputation: 6114

The problem is when you are removing all data

self.searchResults?.removeAll(keepCapacity: false)

you are not reloading tableView, and until self.tableView.reloadData() will be called in Alamofire completion your tableView can crash. You can reload tableView just after removing elements, or just don't remove them, they will be anyway overriden by new on Alamofire completion

Upvotes: 3

Related Questions