Chromium Dioxide Chromium Dioxide - 1 year ago 63
Swift Question

Adding an initializer to a view controller results in an outlet being nil in viewDidLoad

I have a view controller as follows:

class TutorialPageViewController: UIViewController, UIPageViewControllerDelegate
@IBOutlet weak var pageControl: UIPageControl!
var tutorialCategory = TutorialCategory.enableShareContact

override func viewDidLoad()
self.pageViewController.dataSource = self
self.pageViewController.delegate = self
pageControl.numberOfPages = 5


This runs without problem, however after adding an initializer the pageControl outlet is now nil in viewDidLoad resulting in an exception. This is the initializers added:

init(tutorialCategory: TutorialCategory)
super.init(nibName: nil, bundle: nil)
self.tutorialCategory = tutorialCategory

convenience required init(coder aDecoder: NSCoder)
self.init(tutorialCategory: TutorialCategory.enableShareContact)

Why is adding the initializer having this effect of making the IBOutlet now become nil and how do I solve it?

(I tried adding a call to the VC's view within viewDidLoad to attempt to force load the outlet but it had no effect)

Answer Source

Because the outlet is setup by super.init(coder aDecoder: NSCoder), which you are no longer calling.

You probably want:

required init(coder aDecoder: NSCoder) {
    self.tutorialCategory = .enableShareContact
    super.init(coder: aDecoder)

Don't override it as a convenience init.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download