1

Why when I pass data to a UILabel directly in the Second View Controller it turns to be nil but when I pass data to a variable first and then apply it to the UILabel everything works fine?

The following code crash the app after segue performed (theResult is nil):

Second View Controller:

@IBOutlet weak var theResult: UILabel!

Main View Controler:

secondVC.theResult.text = “Nice”

But when I create a variable in the Second View Controller, I can pass the data to it easily and then apply it to the UILabel without any problem:

Second View Controller:

var calculation: String?

@IBOutlet weak var theResult: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        theResult.text = calculation
    }

Main View Controler:

secondVC.calculation = “Nice”

Why is that?

Note: The UILabel has a default value already when it is created in the Storyboard.

I am almost sure that this is not working but I want to know the reason. Why you can easily change for example the background of the Second View Controller like this:

secondVC.view.backgroundColor = .green 

but when you touch the IBOutlets it do not work.

Viaxeen
  • 7
  • 4
  • Where is called `secondVC.theResult.text = “Nice”`? How is created/get `secondVC`? With a Segue? It's because the view hasn't been loaded. The object is initialized, but its Outlet aren't created yet. That's why working with a `String` property (which I'd recommend, be it a "Model") works. You can force a loading, with `secondVC.loadViewIfNeeded()`. – Larme Nov 14 '22 at 09:51
  • I had created the secondVC as a part of segue preparation. If it's because the second view is not loaded and Outlets aren't created, so why the calculation variable works? How calculation variable created if the view hasn't been loaded? – Viaxeen Nov 14 '22 at 10:37
  • For memory efficiency, the view (and the subviews) aren't loaded yet, but the other properties are. See https://stackoverflow.com/questions/5562938/looking-to-understand-the-ios-uiviewcontroller-lifecycle – Larme Nov 14 '22 at 11:29
  • Ok, even if it is not loaded why it crash because of nil? It already have a default value and I confirmed it by running the app. – Viaxeen Nov 15 '22 at 09:12
  • 1
    When not loaded, then `@IBOutlet weak var theResult: UILabel!` is still `nil`. but since you wrote `UILabel!`, it means: If you try to access it and is nil, it will crash. That's why. – Larme Nov 16 '22 at 11:54

0 Answers0