Why can't I access an NSTextField object within viewDidLoad()

150 views Asked by At

Why is it that I get a "Unexpectedly found nil while unwrapping an Optional value" error, suggesting the NSTextField object (text1) is not there if I try to update it during the viewDidLoad() of an NSView class?

class SplitViewController: NSSplitViewController {

@IBOutlet weak var text1: NSTextField!

override func viewDidLoad() {

        super.viewDidLoad()
        text1.stringValue = "View loaded OK"
    }


    @IBAction func buttonPress(_ sender: NSButton) {

        text1.stringValue = "Button was pressed"
    }
}

If I comment out the line text1.stringValue = "View loaded OK" from the viewDidLoad() function then it runs fine and I can access the object using an @IBAction linked to a button on the view - so it is connected OK.

1

There are 1 answers

1
João Fernandes On BEST ANSWER

Taken from this answer.

You will need to unwrap the NSTextField in this case your text1.