views:

43

answers:

1
-(void)viewWillAppear:(BOOL)animated{
//something here
[super viewWillAppear];
}

my question is is this line [super viewWillAppear]; always required? if not when and why do you use it?

+1  A: 

First of all, the correct boiler plate should be:

-(void)viewWillAppear:(BOOL)animated{
   [super viewWillAppear:animated];
   //something here
}

In other words, call super first, then do your own thing. And you have to pass the animated parameter to super.

You usually want to call the super class' implementation first in any method. In many languages it's required. In Objective-C it's not, but you can easily run into trouble if you don't put it at the top of your method. (That said, I sometimes break this pattern.)

Is calling super's implementation required? In the case of this particular method you could get unexpected behavior if you don't call it (especially if you have subclassed a UINavigationController for example). So the answer is no not in a technical sense, but you should probably always do it.

However, in many other methods there may be good reasons for not calling super.

Felixyz
interesting. a lot of code samples i've seen call super last. i wonder why.
Yazzmi
Yes you're right, it's not that uncommon. Would be interesting to hear someone else's insights on this. In this case, it makes absolutely no practical difference, but for example in "loadView" you really should call super first, and on the whole I think it's a very good habit.
Felixyz
I agree that's why it can be quite confusing. SO community please share your thoughts.
Yazzmi
I was under the impression that it is sort of dependent on what you are trying to do. I try and call it after to be safe unless I'm modifying things which will be overwritten by super. There's a similar discussion on an android dev thread which talks about this: http://www.mailinglistarchive.com/html/[email protected]/2010-07/msg00394.html
bjtitus
Here's a counter example: when overriding dealloc, you MUST call super after doing all your own deallocation, otherwise you're almost sure to get a crash. So I guess the truth is that the correct calling order depends on context, which is not ideal.
Felixyz