Everyone tells me "Use super.viewDidLoad() because it's just like that" or "I've been doing it always like that, so keep it", "It's wrong if you don't call super", etc.
override func viewDidLoad() { super.viewDidLoad() // other stuff goes here }
I've only found a few topics about Objective-C cases and they were not so enlightening, but I'm developing in Swift 3, so can any expert give me a good detailed explanation on this?
Is it a case of just good practice or are there any hidden effects?
No, you don't need to call [super viewDidLoad].
In '[super viewDidLoad]', 'super' means the same object as 'self', so the class of this 'super' is B. However, by using 'super', you're telling the compiler that you do not want to invoke class B's 'viewDidLoad' method, but its superclass's 'viewDidLoad'. That means UIView's viewDidLoad, not A's.
viewDidLoad() Called after init(coder:) when the view is loaded into memory, this method is also called only once during the life of the view controller object. It's a great place to do any view initialization or setup you didn't do in the Storyboard.
viewDidLoad() is one of the initialization methods that is called on the initial view controller. viewDidLoad() is called before anything is shown to the user - and it is called only once.
Usually it's a good idea to call super for all functions you override that don't have a return value.
You don't know the implementation of viewDidLoad
. UIViewController could be doing some important setup stuff there and not calling it would not give it the chance to run it's own viewDidLoad
code.
Same thing goes when inheriting from a UIViewController subclass.
Even if calling super.viewDidLoad
doesn't do anything, always calling it is a good habit to get into. If you get into the habit of not calling it, you might forget to call it when it's needed. For example when subclassing a ViewController that depends on it from a 3rd party framework or from your own code base.
Take this contrived example:
class PrintingViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() print("view has loaded") } } class UserViewController: PrintingViewController { override func viewDidLoad() { super.viewDidLoad() // do view setup here } }
Not calling viewDidLoad here would never give PrintingViewController
a chance to run its own viewDidLoad
code
If you don't want to do anything in viewDidLoad
just don't implement it. The super method will be called anyway.
I have a secret, when I worked at Apple I read the source code for UIKit, partly to answer questions I had like this, viewDidLoad
is empty in all the UI*ViewController classes.
Naturally I am not there anymore, they may have changed this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With