Reputation: 15
I have been trying to insert a new row in tableview but it crashes the app whenever I try to do that. I have two view controllers. First controller has the tableview and second controller has some textfields. We add some values from textfields in anarray and then show those values in previous tablview. First time the values gets printed on the tableview but the second time it crashes(it should add a new row and show values on that row).
In first controller:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrObj.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "view") as! ViewCell
cell.label.text = arrObj[indexPath.row].category!
In second controller:
let vc = self.storyboard?.instantiateViewController(identifier: "viewcontroller") as! viewcontroller
vc.arrobj.insert(KeyValues(date: textfeild.text!, category: textfeild.text!, amount: textfeild.text!, tax: textfeild!.text!), at: 0)
vc.tableView.insertRows(at: [IndexPath(row: 0, section: 0)], with: .automatic)// Error: Unexpectedly found nil while implicitly unwrapping an Optional value
self.navigationController?.pushViewController(vc, animated: true)
Can anyone tell where I went wrong?
Upvotes: 0
Views: 294
Reputation: 285260
The problem is that the table view is not connected (yet) right after the controller has been instantiated.
Delete the line to insert the row
let vc = self.storyboard?.instantiateViewController(identifier: "viewcontroller") as! viewcontroller
vc.arrobj.insert(KeyValues(date: textfeild.text!, category: textfeild.text!, amount: textfeild.text!, tax: textfeild!.text!), at: 0)
self.navigationController?.pushViewController(vc, animated: true)
and in the destination controller in viewWillAppear
reload the table view
func viewWillAppear(_ animated : Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
}
There is no benefit to insert the row animated because you won't see it
Upvotes: 1