为什么/什么时候我们必须调用super.ViewDidLoad? [英] Why/when do we have to call super.ViewDidLoad?

查看:140
本文介绍了为什么/什么时候我们必须调用super.ViewDidLoad?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每个人都告诉我使用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
}

我只找到一些关于Objective-C案例的话题,但他们不是如此具有启发性,但我正在开发Swift 3,那么任何专家都可以给我一个很好的详细解释吗?

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?

推荐答案

通常最好为你覆盖的所有没有返回的函数调用super值。

Usually it's a good idea to call super for all functions you override that don't have a return value.

你不知道 viewDidLoad 的实现。 UIViewController可以在那里做一些重要的设置,而不是调用它就不会让它有机会运行它自己的 viewDidLoad 代码。

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.

从UIViewController子类继承时也是如此。

Same thing goes when inheriting from a UIViewController subclass.

即使调用 super.viewDidLoad 没有做任何事情,总是调用它是一个很好的习惯进入。如果你养成不打电话的习惯,你可能会忘记在需要时给它打电话。例如,当从一个第三方框架或你自己的代码库中继承依赖它的ViewController时。

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.

采取这个人为的例子:

class PrintingViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        print("view has loaded")
    }
}

class UserViewController: PrintingViewController {
    override func viewDidLoad() {
    super.viewDidLoad()

     // do view setup here
    }

}

不在这里调用viewDidLoad永远不会给 PrintingViewController 一个机会运行自己的 viewDidLoad 代码

Not calling viewDidLoad here would never give PrintingViewController a chance to run its own viewDidLoad code

如果您不想在 viewDidLoad 中执行任何操作,请不要实现它。无论如何都会调用super方法。

If you don't want to do anything in viewDidLoad just don't implement it. The super method will be called anyway.

这篇关于为什么/什么时候我们必须调用super.ViewDidLoad?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆