致命错误:数组索引超出范围在TableView

问题描述:

你好我有一个动态原型TableView。我添加了4个原型单元。三个是静态的,一个是动态的。问题是我得到数组索引超出范围错误。你能否检查一下哪里出了问题。什么应该是行的总数,我应该分配致命错误:数组索引超出范围在TableView

let NUMBER_OF_STATIC_CELLS = 3 
var labels = ["label1","label2","label3"] 

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


    return labels.count+NUMBER_OF_STATIC_CELLS 



} 

override func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
    return 1 
} 
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 



    var cell: TestViewCell! 

    print(indexPath.row) 
    if (indexPath.row == 0) { 
     cell = tableView.dequeueReusableCellWithIdentifier("static1", forIndexPath: indexPath) as! TestViewCell 


    } 

    if (indexPath.row == 1) { 
      cell = tableView.dequeueReusableCellWithIdentifier("static2", forIndexPath: indexPath) as! TestViewCell 
     //cell.cardSetName?.text = self.cardSetObject["name"] as String 
     } 

    if (indexPath.row == 2) { 
      cell = tableView.dequeueReusableCellWithIdentifier("static3", forIndexPath: indexPath) as! TestViewCell 
      //cell.cardSetName?.text = self.cardSetObject["name"] as String 
     } 




     if (indexPath.row >= 3) { 

     cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TestViewCell 
     cell.testLabel.text = labels[indexPath.row] // return test rows as set in numberOfRowsInSection 
    } 

    return cell; 
    } 
+1

FYI,苹果在他们的Swift文件注释常数应该颠倒骆驼情况.....并非所有帽。这只是一个C的东西:/。为你的行检查使用开关盒,这将清理你的代码..很多。 – TheCodingArt

+0

仍旧损坏,更新后的逻辑尝试访问索引3,4和5,这些索引超出了范围。尝试'标签[indexPath.row - NUMBER_OF_STATIC_CELLS]'。还要将'> = 3更改为> = NUM​​BER_OF_STATIC_CELLS'。另外,@TheCodingArt关于常量情况的说法 –

+0

另外,我强烈建议你花更多的努力来保持缩进的一致性 - 当你不这样做时,让自己变得更难 - 你所有的if都应该缩进同一级别 - 扫描你的代码的人看起来像你嵌套'ifs'当你不 –

您已设置细胞的数量将是6和标签阵列,你只有3个单元。此外,在你分配给单元格的每个条件中,但在方法的最后,你将覆盖那个(我想)不是你的意图。然后,您尝试访问超出索引的索引

+0

对不起,我已经更新了我的问题。请看看 – hellosheikh

+0

还是一样的问题。在最后一个条件中,您正在访问索引3,4 ...中只有3个元素的数组中的元素。这就是您的应用崩溃的原因。把断点和检查值,你会发现这个问题 –

+0

所以我应该怎么办?还有我有三个静态的细胞和细胞的其余部分将是动态的。所以这意味着第四之一。请你能告诉我应该有多少行定义。 – hellosheikh

这是您的错误!你有没有标签索引2以上。下面的行试图做标签[3]等

cell.testLabel.text = labels[indexPath.row]