【问题标题】:While UISearchBar is active,scrolling to UITableView app get crashes当 UISearchBar 处于活动状态时,滚动到 UITableView 应用程序会崩溃
【发布时间】:2016-02-26 06:47:41
【问题描述】:

我的应用程序运行良好,但突然当我点击UISearchBar 并且当我向下滚动UITableView 时没有输入,然后应用程序崩溃并出现以下错误:Thread1 : EXC_BAD_INSTRUCTION

但是当我点击UISearchBar 并输入一些文本时,然后当我向下滚动UITableView 时,应用程序运行正常,它不会崩溃。

最后,当我点击UISearchBar 并输入一些文本并删除所有这些文本时,当我向下滚动UITableView 时,应用程序运行正常,它不会崩溃。

此函数发生错误:

 func tableView(historyTableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = historyTableView.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell;
        //self.historyTableView.scrollEnabled = true
        if(searchActive){
//...Error occurs over here ==>> Thread1 : EXC_BAD_INSTRUCTION
            cell.textLabel?.text = filtered[indexPath.row]  
        } else {
            cell.textLabel?.text = data[indexPath.row]
        }

        return cell;
    }

【问题讨论】:

  • 你能显示你的完整堆栈跟踪吗
  • 使用异常断点将帮助您找出崩溃的确切位置。
  • 当您的过滤数组中的任何错误存在于您在表格视图中滚动的索引时,可能会发生这种情况,请检查过滤数组元素。

标签: ios uitableview swift2 uisearchbar


【解决方案1】:

我的猜测是,当您开始主动搜索时,您并没有重新加载表格。我也猜想nunberOfRowsInSection: 不处理主动搜索的情况。如果这些情况属实,那么只要您滚动到大于filtered.count 的行,调用filtered[indexPath.row] 就会使您的应用崩溃

【讨论】:

  • 你的numberOfRowsInSection: 方法是什么样的?
【解决方案2】:

希望你也用numberOfRowsInSection 方法处理了filtereddata 数组。

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if(searchActive){

        return filtered.count

    }else{

        return data.count
    }
}

现在您只需在点击 UISearchBar 时将您的 searchActive 设置为 true

func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
    searchActive = true;
} 

希望这会有所帮助!

【讨论】:

    【解决方案3】:

    通过这种方式,我已经克服了这个问题。

    func tableView(historyTableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
            let cell = historyTableView.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell;
            if(searchActive){
                if(searchBar.text=="")
                {
                    //do nothing
    
                }else{
                    cell.textLabel?.text = filtered[indexPath.row]
                }
    
            } else {
                cell.textLabel?.text = data[indexPath.row]
            }
    
            return cell;
        }
    

    【讨论】:

    • 现在应用在滚动时不会崩溃,因为我已经通过添加条件来处理这个问题,如果 seachbar 为空则什么都不做。
    猜你喜欢
    • 2012-12-07
    • 2014-06-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-21
    • 1970-01-01
    • 2016-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多