-1

I have my viewcontroller where I define my button in this way:

@IBOutlet weak var myButton: UIButton!

in viewDidLoad I am going to hide it in this way:

myButton.hidden = true    

In iOS 9 all ok and in iOS 8 I got this error:

fatal error: unexpectedly found nil while unwrapping an Optional value

where am I wrong? I tried to check all the outlet references and it's all ok... I tried also to connect and disconnect it but I can't find the error

cyclingIsBetter
  • 17,447
  • 50
  • 156
  • 241
  • try instead of putting in `viewDidLoad`, put in the IBOutlet's `didSet` and see if its solved, about your bug then i have no idea though – Tj3n Aug 22 '16 at 03:50

2 Answers2

-1

The most obvious answer is usually the correct answer: the variable is nil. What would cause this to be true on iOS 8 and not on iOS 9? It must be a difference in the SDK or runtime environment.

If you are encountering this in the viewDidLoad then your button is probably being freed. If I would venture a guess, I suspect your button is not part of the view hierarchy (at least for a moment) and is being freed. This would explain all the symptoms.

If you are adding and removing the button, you should make the outlet strong (the default) instead of weak.

Holly
  • 5,270
  • 1
  • 24
  • 27
  • You are completely right. Can you explain well what do you mean that my button is not part of the view hierarchy? – cyclingIsBetter Aug 22 '16 at 04:05
  • In simple terms, the view hierarchy is what is contained in your root window. When your view controller is visible, it's root `view` and all of its subviews are within the view hierarchy. The reason this is important is that each view retains its subviews to prevent them from being deallocated. Once you call `removeFromSuperView`, they get released. If nothing else is retaining them (such as a strong outlet), they will be freed. – Holly Aug 22 '16 at 06:11
  • Why did this get down voted? Feedback would be appreciated if you feel the answer is bad enough to down vote. – Holly Aug 22 '16 at 20:22
-1

adding these stuff I solved:

override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
        super.init(nibName: "MyViewController", bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
cyclingIsBetter
  • 17,447
  • 50
  • 156
  • 241