Ad

TableView Not Updating After Todo Is Added To Array

- 1 answer

I am trying to create a todo app in Swift. But there is a problem. When someone presses the addTodo button, it adds todo to the todos array. Then I reload the tableView. But it doesn't show the new todo on screen. 


class ViewController: UIViewController {

    @IBOutlet weak var searchBar: UISearchBar!
    @IBOutlet weak var inputBar: UITextField!
    @IBOutlet weak var tableView: UITableView!
    
    var todo : [String] = ["abc", "def", "dhe"]
      
    func reload() {
        DispatchQueue.main.async {
            self.tableView.reloadData();
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.register(UINib(nibName: "Cell", bundle: nil), forCellReuseIdentifier: "cell");
        tableView.dataSource = self
    }
    
    @IBAction func addTodo(_ sender: UIButton) {
        if var todo = inputBar.text {
            print(todo);
            todo.append(todo)
            reload()
        }
    }
}

extension ViewController : UITableViewDataSource {
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! Cell;
        cell.task.text = todo[indexPath.row];
        print("Running");
        return cell;
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return todo.count;
    }
}

Ad

Answer

This is a very funny mistake.

In addTodo you append the value of the local variable todo to itself rather than to the array with the same name which is actually self.todo.

Name arrays always in plural form – or at least with a different name – to avoid this kind of confusion

var todos : [String] = ["abc", "def", "dhe"]

However, as the text property of UITextField is never nil you can simply write

@IBAction func addTodo(_ sender: UIButton) {
    todos.append(inputBar.text!)
    reload()
}
Ad
source: stackoverflow.com
Ad