简体   繁体   English

停止 tableView.reloadData() 抛出错误?

[英]Stop tableView.reloadData() throwing an error?

I am following a tutorial for a simple list app, where you add items to a list via UITextField.我正在关注一个简单列表应用程序的教程,您可以在其中通过 UITextField 将项目添加到列表中。 However, it crashes at tableView.reloadData() and I don't know why.但是,它在 tableView.reloadData() 崩溃,我不知道为什么。 Making tableView optional causes it to not crash, but it also causes the app to not add the item to the list.将 tableView 设为可选会导致它不会崩溃,但也会导致应用程序无法将项目添加到列表中。 Here is the class code:这是 class 代码:

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {
    struct todo {
        var text: String
        var isDone: Bool
    }

    var todos = [todo]()
    @IBOutlet var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        todos.append(todo(text: "test", isDone: false))
    }

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "todo-cell", for: indexPath)
        let todo = todos[indexPath.row]
        cell.textLabel?.text = todo.text
        if todo.isDone {
            cell.accessoryType = .checkmark
        } else {
            cell.accessoryType = .none
        }
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)

        var todo = todos[indexPath.row]
        todo.isDone = !todo.isDone
        todos[indexPath.row] = todo
        tableView.reloadRows(at: [indexPath], with: UITableView.RowAnimation.automatic)
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        todos.append(todo(text: textField.text!, isDone: false))
        tableView.reloadData() // Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value... crashes here!!
        textField.text = ""
        textField.resignFirstResponder()
        return true
    }
}

My first guess is that you have not linked the tableview in your storyboard to your view controller.我的第一个猜测是您没有将 storyboard 中的表格视图链接到您的视图 controller。

Maybe you should check this first.也许你应该先检查一下。 Put a break point in viewDidLoad to see if your tableview has been set.在 viewDidLoad 中放一个断点,看看你的 tableview 是否已经设置好了。 If its nil, then there is your problem.如果它为零,那么这就是你的问题。

tableView object is nil. tableView object 为零。

@IBOutlet var tableView: UITableView! // is not link with viewController

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM