我的同事有时会在覆盖ios方法时调用super,有时候不会.这似乎主要基于他们的经验.在决定是否打电话给超级时,是否有经验法则?
例如:
// Has super override func awakeFromNib() { super.awakeFromNib() } // No super override func drawRect(rect: CGRect) { }
解决方法
对于是否应该调用给定方法的超级实现,实际上没有经验法则.这应该根据具体情况确定,具体取决于超类的实施方法文档中的建议以及您的要求.
只是为了解释为什么你所包含的两个例子可能是它们的方式,我们可以查看-[UIView drawRect:]的文档,其中指出:
If you subclass UIView directly,your implementation of this method@H_403_14@ does not need to call super. However,if you are subclassing a@H_403_14@ different view class,you should call super at some point in your@H_403_14@ implementation.
以及-[NSObject awakeFromNib]的文件,其中规定:
You must call the super implementation of awakeFromNib to give parent@H_403_14@ classes the opportunity to perform any additional initialization they@H_403_14@ require. Although the default implementation of this method does@H_403_14@ nothing,many UIKit classes provide non-empty implementations.
大多数情况下,你可以安全地打电话给方法的超级实现(见下面的评论).但是,请注意,某些方法要求您调用其超级实现,有些则不需要,有些方法甚至要求您在覆盖中的特定点调用超级实现.所以请记住,如有疑问,请务必查阅文档.