When to use super when overriding ios methods

前端 未结 2 1343
栀梦
栀梦 2021-02-04 11:07

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 d

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-04 11:14

    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.

提交回复
热议问题