0

I got the following error.

fatal error: unexpectedly found nil while unwrapping an Optional value
2017-09-20 23:08:46.626918+0400 UnitConverter[6852:10110844] fatal error: unexpectedly found nil while unwrapping an Optional value

Code and Image attached.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let webVC = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "webVC") as! ViewController
        webVC.lblCategory.text = self.uc.categories[indexPath.row]
    }

enter image description here

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Jamal Abdul Nasir
  • 2,557
  • 5
  • 28
  • 47
  • 2
    Something is nil that shouldn't be. In this case, `lblCategory` because, as Sulthan says below, the view hasn't been loaded so the connection hasn't been set up. – Kevin Sep 20 '17 at 19:21
  • 1
    @Kevin Nah, he's accessing an outlet before the view has been loaded (since he is not accessing the `view` or calling `loadViewIfNeeded`). – Sulthan Sep 20 '17 at 19:22
  • @Sulthan Ah yes, that would do it. – Kevin Sep 20 '17 at 19:23
  • I bind the display of webVC from interface builder. I dragged the table cell to the view and bind show to it. so what is the workaround to fix this issue. @Sulthan – Jamal Abdul Nasir Sep 20 '17 at 19:31
  • @JamalAbdulNasir Call `webVC.loadViewIfNeeded()` before accessing `lblCategory`. – Sulthan Sep 20 '17 at 19:38
  • Make sure you have connected `lblCategory` label in the `webVC` storyboard. – Sulthan Sep 20 '17 at 19:43
  • @Sulthan If the author removes that line and the `lblCategory` isn't correctly set, that should crash at some point, if he tries on use it on its code in `viewDidLoad()` doing `self.lblCategory = "Test"`. It could help then understand where lies the issue exactly. – Larme Sep 20 '17 at 19:51
  • @Larme i tested that already. and it is working. – Jamal Abdul Nasir Sep 20 '17 at 19:52
  • And...? Does it crashes? If on the line `self.lblCategory = "Test"`? If yes, that's the issue. If not, is `self.uc.categories[indexPath.row]` nil? Also, did you try by setting a String property `categoryText`, do instead `webVC.categoryText = self.uc.categories[indexPath.row]`, and on viewDidAppear() (or else), do `self.lblCategory.text = categoryText`? – Larme Sep 20 '17 at 19:55

2 Answers2

0

Outlets are connected when the view is loaded. The view is loaded when the view is first accessed.

Before you don't load the view webVC.lblCategory will be nil, crashing your app. To fix it either access the view first:

_ = webVC.view
webVC.lblCategory.text = ...

or load the view explicitly

webVC.loadViewIfNeeded()
webVC.lblCategory.text = ...
Sulthan
  • 128,090
  • 22
  • 218
  • 270
0

You could use a string property in your view controller and set the string property from table view didselect. Then in you view controller, you can set value to your label outlet.

Sujan
  • 147
  • 1
  • 3