Dileep
Dileep

Reputation: 2425

Custom view - Crash in "required init?(coder aDecoder: NSCoder)" method

Code:

class HeaderView: UIView {

@IBOutlet weak var titleLabel: UILabel!

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    finishInit()
}

func finishInit() {
    titleLabel.backgroundColor = UIColor.white
}

func setView(withTitle title: String?) {
    titleLabel.backgroundColor  = UIColor.white
    titleLabel.text = title

}

Crash:

On finishInit() method, while setting label background color

fatal error: unexpectedly found nil while unwrapping an Optional value

But same, on setView() method, is not crashing.

Upvotes: 3

Views: 1848

Answers (1)

Thomas Krajacic
Thomas Krajacic

Reputation: 2747

When the init methods run and return, the connections of the outlets are not yet made. Therefore the outlets are still nil and you are crashing when using it.

You should be able to test this by adding a question mark (?) after the titleLabel and thus treating it like an optional again.

titleLabel?.backgroundColor = UIColor.white

Then you will not crash but the line will also not do anything of course if the label is still nil.

So you need to call the code that uses the outlets later (which you seem to be doing with setView?

You might use awakeFromNib where the outlets should be set.

Upvotes: 8

Related Questions