何时覆盖iOS方法时使用Super [英] When to use super when overriding ios methods

查看:96
本文介绍了何时覆盖iOS方法时使用Super的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当覆盖ios方法时,我的同事有时会调用super,而有时则不会.这似乎主要是基于他们的经验.决定是否调用超级时是否有经验法则?

My coworkers will sometimes call super when overriding an ios method and sometimes not. This seems to be mostly based on their experience. Is there a rule of thumb to use when deciding whether or not to call super?

例如:

// Has super
override func awakeFromNib() {
    super.awakeFromNib()
}

// No super
override func drawRect(rect: CGRect) {
}

推荐答案

对于您是否应该调用给定方法的超级实现,实际上并没有经验法则.这应该根据具体情况确定,具体取决于文档中有关超类实现该方法的建议以及您的要求.

There isn't really a rule of thumb for whether or not you should call the super implementation of a given method. This is something that should be determined on a case by case basis, depending on recommendations from the documentation for the superclass' implementation of that method, and your requirements.

仅是为了解释为什么您包括的两个示例可能是它们的样子,我们可以查看

Just to explain why the two examples you included might be the way they are, we can look at the documentation for -[UIView drawRect:], which states:

如果直接子类化UIView,则此方法的实现 不需要调用超级.但是,如果您将一个子类 不同的视图类,您应该在您的某个时候调用super 实施.

If you subclass UIView directly, your implementation of this method does not need to call super. However, if you are subclassing a different view class, you should call super at some point in your implementation.

以及

您必须调用awakeFromNib的超级实现才能给父级 给他们机会进行任何其他初始化 要求.尽管此方法的默认实现确实 没有,许多UIKit类提供了非空的实现.

You must call the super implementation of awakeFromNib to give parent classes the opportunity to perform any additional initialization they require. Although the default implementation of this method does nothing, many UIKit classes provide non-empty implementations.

在大多数情况下,您应该调用方法的超级实现是一个安全的选择(请参阅下面的评论).但是请注意,有些方法要求您调用其超级实现,有些则不需要,甚至有些要求您在覆盖中的特定点调用超级实现.因此,请记住,如有疑问,请始终查阅文档.

Most of the time, it's probably a safe bet that you should call the super implementation of a method (see comments below). However, be warned, some methods require you to call their super implementation, some don't, and some even require you to call the super implementation at a specific point in your override. So remember, when in doubt, always consult the documentation.

这篇关于何时覆盖iOS方法时使用Super的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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