I've been coding for some years now, and I'm very used to always calling a method's super constructor when overriding it. But recently I've been wondering if it's always necessary... I get that when you override an initialiser you should call super.init()
. But in Swift and iOS development, if you override a UIViewController
lifecycle method like viewDidLoad()
and forget to call super.viewDidLoad()
, the compiler dosen't produce any warning or error and the code seems to be compiling fine. So I was wondering if the call is somehow build into the SDK, and if it's even necessary to make (with in mind that we want to make the code as efficient and correct as possible)?
Asked
Active
Viewed 1,437 times
1

Nikolaj Simonsen
- 1,650
- 3
- 18
- 34
3 Answers
2
I think you may look here a nice answer.
Apple doesn't restrict you to call super.viewDidLoad()
, but it won't be safe to use some view cycle methods and variable before it's call. If you want first to init your own vars or properties for example - I think, it won't be a problem.

Community
- 1
- 1

katleta3000
- 2,484
- 1
- 18
- 23
0
Yes, you should always call super.
Here is what I do alwyas
// MARK: - Controller life cycle stack
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewWillAppear(animated: Bool)
{
super.viewWillAppear(animated)
setupNavigationBar()
}
override func viewDidAppear(animated: Bool)
{
super.viewDidAppear(animated)
}

swiftBoy
- 35,607
- 26
- 136
- 135
-
Me too (except from overriding methods without doing anything in them, but I guess that's just to give an example)... But what I'm looking for is some documentation on why you need it (not in general, but for iOS). If you write `override func viewDidLoad() { self.doSomething() }` it'll compile and work just fine... So why even call `super.viewDidLoad()`? Is it redundant? – Nikolaj Simonsen Dec 01 '15 at 08:10
0
So, after a while I experienced first hand what might happen if I did not always call super:
Let's say you have two viewControllers
class ViewControllerA: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.doSomethingImportant()
}
}
class ViewControllerB: ViewControllerA {
override func viewDidLoad() {
self.doSomethingLessImportant()
}
}
Now you expect that when you push to ViewControllerA
it'll call doSomethingImportant()
, but in most cases that will not happen, because you forgot to call super.viewDidLoad()
in ViewControllerA
.

Nikolaj Simonsen
- 1,650
- 3
- 18
- 34