`[super viewDidLoad]` 约定 [英] `[super viewDidLoad]` convention

查看:25
本文介绍了`[super viewDidLoad]` 约定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到一些示例代码,在您的实现之前和之后都调用了 [super viewDidLoad].

I see some example code with [super viewDidLoad] called before your implementation and after your implementation.

我知道您不必总是调用 super(如在许多其他讨论中所见).当你调用它时,它是在你编码之前还是之后?

I know you don't always have to call super (as seen in many other discussions). When you do call it, is it expected before or after you code?

这可能会产生后果,具体取决于 super 的实现方式.尽管您不必知道 super 的实现来编写您的实现.

This could have consequences depending on what super's implementation does. Though you shouldn't have to know super's implementation to write yours.

当然这适用于所有 UIViewControllers 委托方法(willAppear、didAppear 等...)

Of course this goes for all of UIViewControllers delegate methods (willAppear, didAppear, etc...)

有什么想法吗?

推荐答案

我的经验法则是:如果你正在做一些与初始化相关的事情,总是首先调用超类的方法(如果你打算调用它).这使超类有机会进行您稍后在方法中可能依赖的任何设置.如果您正在做一些与销毁相关的事情,请最后调用超类的方法.这确保您可以在整个方法的执行过程中依赖对象的状态.最后,根据具体情况考虑任何其他情况.例如,如果您正在处理一个事件,您可能希望首先处理该事件,并且仅在您选择不处理该事件或者您以某种方式更改它并希望将其传递给事件时才调用超类的方法链.

My rule of thumb is: if you're doing something related to initialization, always call the super class's method first (if you are going to call it at all). This gives the super class a chance to do any set-up that you may be relying on later in your method. If you're doing something related to destruction, call the super class's method last. This makes sure that you can rely on the state of the object throughout the execution of your method. Finally, take any other case on a case-by-case basis. For instance, if you're handling an event, you probably want to deal with the event first, and only invoke the super class's method if you chose not to handle the event or if you somehow altered it and want to pass it along the event chain.

这篇关于`[super viewDidLoad]` 约定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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