user5278445
user5278445

Reputation:

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. However, it crashes at tableView.reloadData() and I don't know why. Making tableView optional causes it to not crash, but it also causes the app to not add the item to the list. Here is the class code:

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
    }
}

Upvotes: 0

Views: 175

Answers (2)

SGDev
SGDev

Reputation: 2252

tableView object is nil.

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

Upvotes: 1

David Thorn
David Thorn

Reputation: 129

My first guess is that you have not linked the tableview in your storyboard to your view controller.

Maybe you should check this first. Put a break point in viewDidLoad to see if your tableview has been set. If its nil, then there is your problem.

Upvotes: 1

Related Questions