@IBOutlet weak var mainTableView: UITableView!
var taskArray: [Task]? = nil

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 10
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "mainCell") as! mainCell

    taskArray = CoreDataHandler.fetchObject()

    let task = taskArray![indexPath.row]

    cell.titleLabel.text = task.title
    //cell.dateLabel.text = String(task.date)

    return cell
}

我总是在以下行得到错误:“线程1:致命错误:索引超出范围”:let task = taskArray![indexPath.row]。有人可以帮我吗?

最佳答案

您必须在此处发送数组计数,不要返回静态数字,因为它可能超出数组计数

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  return taskArray.count
}

//也转换
var taskArray = [Task]()

//

提取应该在viewDidLoad
override func viewDidLoad()  {
   super.viewDidLoad()
   taskArray = CoreDataHandler.fetchObject()
}

不在cellForRowAt

关于ios - Swift 3中的索引超出范围,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50774506/

10-08 21:07