9

I have always thought that calling [super viewWillAppear:animated] is mandatory. But today I came across a piece of code from Apple's example application called CoreDataBooks and here's viewWillAppear: implementation from there:

- (void)viewWillAppear
{
   [self.tableView reloadData];
}

Note there is no call to super. This confuses me a lot. If even Apple's code doesn't include call to [super viewWillAppear:] then maybe I can always omit it? Or maybe there are certain rules about this matter? Can anybody explain it?

Carl Veazey
  • 18,392
  • 8
  • 66
  • 81
Andrey Chernukha
  • 21,488
  • 17
  • 97
  • 161

2 Answers2

14

Even though not calling the super implementation can be harmless sometimes, you should ALWAYS call [super viewWillAppear:], regardless of the bad examples Apple publishes. Not doing it may lead to very nasty issues to track down.

According to the documentation

If you override this method, you must call super at some point in your implementation.

The specific example you mentioned is broken in a more subtle way: they implemented viewWillAppear instead of viewWillAppear:, so that piece of code is not even being executed!

Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235
  • 1
    I have forgotten call super implementation many times. It's pity that Xcode doesn't give warnings about that – Leszek Zarna Sep 28 '13 at 08:52
  • Well Xcode warnings are at a complete different level. Here we are talking about framework usage, so it's not an Xcode matter. – Gabriele Petronella Sep 28 '13 at 15:57
  • Can you elaborate on the kinds of issues this may cause, and the reasons behind them? Thanks – Bradley Thomas Aug 28 '14 at 14:42
  • 1
    @BradTHomas, in short, the superclass implementations of `viewDidLoad`, `viewWillAppear` and similar methods often provide some basic (but vital) functionalities, such as setting up observers, subviews, constraints, etc... Failing to call `super` before your custom code, can result in uninitialized views, inconsistent state and other similar amenities. In most cases, nothing terrible will happen, but the one time you face this issue you'll be terribly confused. When in doubt, just call super and be done with it. – Gabriele Petronella Aug 28 '14 at 15:11
  • 3
    @LeszekŻarna, If you turn on the __Static Analyzer__ in your project you do get an issue if you forget to call it :) (e.g. `The 'viewDidAppear:' instance method in UIViewController subclass 'MyViewController' is missing a [super viewDidAppear:] call`) – Iulian Onofrei Dec 18 '14 at 10:19
5

in short: always.

if you don't that can cause issues that are hard to track

Daij-Djan
  • 49,552
  • 17
  • 113
  • 135