Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use super when overriding ios methods

Tags:

ios

swift

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?

Ex:

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

// No super
override func drawRect(rect: CGRect) {
}
like image 286
Joe Susnick Avatar asked Jul 31 '16 22:07

Joe Susnick


1 Answers

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:

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.

and the documentation for -[NSObject awakeFromNib], which states:

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.

like image 138
Mick MacCallum Avatar answered Oct 27 '22 04:10

Mick MacCallum