Search code examples
swiftcocoaiboutletnsviewcontrollernsstackview

NSViewController IBOutlet is always nil


I have a Cocoa app that has a main NSWindowController and inside a NSView connected to a NSViewController object like this:

enter image description here

CloudCardsViewController is a NSViewController with its Nib and IBOutlet to a NSStackView. When I try to access to the outlet, app crashes and show this error on console:

fatal error: unexpectedly found nil while unwrapping an Optional value 2017-09-16 19:46:43.756852+0200 AppName[3402:150754] fatal error: unexpectedly found nil while unwrapping an Optional value

If I add NSViewController by code, works fine...

Here is the code: enter image description here

If I print baseStackView the result is nil

Any idea? Thanks!


Solution

  • The problem with your code is that you only load the MainWindowController from the XIB file. The MainWindowController gets initialised and with it only the connected XIB from the CloudCardsViewontroler. But your CloudCardsViewController was never actually initialised for itself. You cannot use your CloudCardsViewController like this. You need to initialise it and then add it to your MainWindowController.

    You instantiated your class directly with the initializer. The outlets won't connect this way. The Interface Builder creates customized instances of your classes and encodes those instances into NIBs and Storyboards for repeated decoding, it doesn't define the classes themselves.