views:

152

answers:

2

Does it matter if I call the method of the super class first thing or at the end? For example

-(void)didReceiveMemoryWarning {
   /* do a bunch of stuff */

   [super didReceiveMemoryWarning];
}

versus

-(void)didReceiveMemoryWarning {
   [super didReceiveMemoryWarning];

   /* do a bunch of stuff */
}

same question for other methods like viewWillAppear, willRotateToInterfaceOrientation etc.

I am looking for meaningful differences, not just stylistic, or philosophical (although those are welcome too).

+6  A: 

It depends on functionality, you either want to do something after the super class did its thing or before.

For example if superclass holds some UI elements and you extend it and your class will hold some more UI elements. To get the size to fit your whole object you would probably call super class to calculate the size of its elements and then you add to that size the size of the elements that you added.

It would not make sense otherwise - super class is not aware of your elements so it would overwritten your calculation. Again, this depends on implementation.

There's a specific case where you need to call super method as last thing:

-(void)dealloc
{
    ...
    [super dealloc];
}
stefanB
+4  A: 

Typical Cocoa convention:

  1. If you are performing setup, call super FIRST
  2. If you are performing teardown, call super LAST

So, initialization, viewDidLoad, etc.. fall under the first case. Memory warnings, viewDidUnload, and dealloc fall under the second case.

You should also design your classes to follow this convention. Any deviations should be specifically noted.

Related SO answer:

http://stackoverflow.com/questions/844195/super-viewdidload-convention/844305#844305


To add: The rationale for calling super first during setup, is that you want to make sure everything is in place before you extend functionality. The corollary, is that when you are deallocating, you don't want any superclass ivars your subclass depends on to be dealloced before you have a chance to handle them.

This makes sense in reference to UI updates as well as noted in the comments below.

Corey Floyd
how would you classify willRotateToInterfaceOrientation in that assessment?
fnCzar
In my opinion, I would say it is setup. I would think you want the super class to perform rotations of it's objects (which most likely includes the root view object) and then you would want to handle yours (which are most likely subviews) after that occurs.
Corey Floyd