3

I have created a standard outlet for a view that will hold different information based on the button selected on the previous screen.

@IBOutlet weak var labelView: UIView!

It shows it is connected in both the story board view and on the code itself, however, every time I get to any reference to the labelView such as:

if detail.description == "About"
{
   labelView.backgroundColor = UIColor.red
}

Then the app crashes out with:

fatal error: unexpectedly found nil while unwrapping an Optional value

I have tried everything I can think of or read on the internet:

  • Removed and replaced the connection

  • Deleted the derived data folder like one post suggested

  • Created a reference to self.view to force it to load

  • Moved it to viewDidAppear

  • Moved it to viewWillAppear

  • Moved it to viewDidLoad (which is where it is currently being
    called)

I am sure at this point that the answer is rather simple and I am just completely missing it.

Alessandro Ornano
  • 34,887
  • 11
  • 106
  • 133
Danickar
  • 85
  • 7
  • Can you please show the backtrace so we can get a better idea of what's happening? Exactly which line is it crashing on? – Ashley Mills Jan 23 '17 at 17:26
  • 1
    I'm sorry if I ask you a simple question: are you sure you have the crash in that line? Have you try to put a breakpoint and proceed step by step to see if is it really the crash line? – Alessandro Ornano Jan 23 '17 at 17:27
  • Are you removing the view from its superview at some point? – Sulthan Jan 23 '17 at 17:31

2 Answers2

1

To see where the outlet is being set to nil, try this:

@IBOutlet weak var labelView: UIView? {
    didSet {
        print("labelView: \(labelView)")
    }
}

You should see it set to an initial value when the view is loaded. If it then gets set to nil, put a breakpoint on the print and your should be able to see from the backtrace where it's happening.

Ashley Mills
  • 50,474
  • 16
  • 129
  • 160
  • 1
    Adding that and checking through the back trace (again) I finally found the simple and stupid error. I was modifying a previous project and missed a call to a function that was referencing the view from the segue before the view did load, therefore nil. I do feel very foolish now. – Danickar Jan 23 '17 at 18:26
0

Views are lazy initialized. In case you are calling the affected line of code before viewDidLoad() in the views life cycle, try to access viewin advance:

if detail.description == "About" {
    _ = self.view
    labelView.backgroundColor = UIColor.red
}
shallowThought
  • 19,212
  • 9
  • 65
  • 112