表格视图cellForRowAt中单元格的索引超出范围

时间:2020-06-25 00:37:18

标签: swift

我有一个视图控制器,该控制器应显示歌曲和艺术家。每当我运行代码时,它都会给我一个线程1:致命错误:艺术家的索引超出范围。我试图从我的sql数据库中的2个表中获取信息,它们被称为搜索和艺术家。我做了和搜索相同的工作,并且可以,但是现在我添加了艺术家,我崩溃了。任何帮助将不胜感激。

pull

searchBar函数:

var searchActive: Bool = false
var search = [Search]()
var artist = [Artist]()

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for:  indexPath)
    
    if  (searchActive) {
        cell.textLabel?.text = search[indexPath.row].cleanName
        cell.textLabel?.text = artist[indexPath.row].artistName //CRASH
    } else {
       searchActive = true
    }
    return cell;
}
  
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    
    return search.count;
}

1 个答案:

答案 0 :(得分:1)

尝试一下。它不会崩溃,因为如果您的数组为nil或没有数据,它将得到管理。在numberOfRowsInSection所用的三元条件下,它将设置最大计数,因此不会在cellForRowAt indexPath 崩溃。


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for:  indexPath)
    
    if  (searchActive) {
        cell.textLabel?.text = search[indexPath.row].cleanName
        cell.textLabel?.text = artist[indexPath.row].artistName ?? "No Data"
    } else {
       searchActive = true
    }
    return cell;
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    
   if  (searchActive) {
        return search.count > artist.count ? search.count : artist.count
    }
    else{
        return artist.count 
//Note here you can return anything once your search is not active. or just return 0 to show blank results. 

     }

}

希望它对您有用!

相关问题