何时覆盖iOS方法时使用Super [英] When to use super when overriding ios methods
问题描述
当覆盖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.