Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
409 views
in Technique[技术] by (71.8m points)

ios - Why/when do we have to call super.ViewDidLoad?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...