When to use super when overriding ios methods

My colleagues sometimes call super when overriding the ios method, and sometimes not. This seems to be mainly based on their experience. Is there a rule to use when deciding whether to call super?

Example:

// Has super override func awakeFromNib() { super.awakeFromNib() } // No super override func drawRect(rect: CGRect) { } 
+7
ios swift
source share
2 answers

Actually there is no right rule for whether you should name a super-implementation of this method. This is something that should be determined on an individual basis, depending on the recommendations from the documentation for implementing this superclass method and your requirements.

To explain why the two examples you included can be what they are, we can look at the documentation for - [UIView drawRect:] , which reads:

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

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

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

In most cases, this is probably a safe bet that you should call a super-implementation of the method (see comments below). However, be careful, some methods require you to call them a super implementation, some do not, and some even require you to call a super implementation at some point in your redefinition. Therefore, remember when you are in doubt, always refer to the documentation.

+5
source share

Sending a super message is a way to call the implementation method defined by the superclass further down the inheritance chain. The most common use of super is overriding a method. Calling super will allow the parent class to do some preparation. If you redefine a method, you should call super else you might have some kind of invalid state, because the implementation of the superclass missed the initialization of some states.

0
source share

All Articles