0

I am calling cellForRowAtindexPath manually in a textFieldShouldReturn from a view controller, and the arguments for cellForRowAtindexPath are tableViewOutlet and indexPath ("index" in this example). Here both cellForRowAtindexPath and tableViewOutlet are from another view controller, I'm calling them by using instance.

Once cellForRowAtindexPath calling it showing error like:

unexpectedly found nil while unwrapping an optional value.

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    if(textField == carRating){
        let rating = Float(textField.text!)
        secondInstanceForMyData.masterCarData[index.row].carRating = rating
        let _: MyTableViewCell = myViewControllerInstance.tableView(myViewControllerInstance.tableViewWillLoad as UITableView, cellForRowAt: index) as! MyTableViewCell
    }
    return true
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Harsha
  • 760
  • 1
  • 7
  • 21
  • 1
    Possible duplicate of [What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?](https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – Tamás Sengel Oct 08 '17 at 17:06
  • Means there is no data in variable from where we are fetching – Harsha Oct 08 '17 at 17:08
  • What is the point of the line that starts with `let _: MyTableViewCell = ...` ? – rmaddy Oct 08 '17 at 17:09
  • Which line exactly is causing the error? – rmaddy Oct 08 '17 at 17:09

1 Answers1

0

What you're calling here is the tableview data source method tableView(tableView:cellForRowAt:), which should never be called by you, it has to be implemented by you. Think of it this way, this method needs to provide a cell for the table view, not ask for it.

If you want to get a cell from an already populated tableview, call the tableview method cellForRow(at:)

let indexPath = IndexPath(row: 0, section: 0)
if let cell = tableView?.cellForRow(at: indexPath) as? MyTableViewCell {
    // do something with the cell
}

And if you want to update your tableview, then you need to update your data source and either call reloadData() on your tableview or call one of the update methods.

Au Ris
  • 4,541
  • 2
  • 26
  • 53