Is the time of calling a superclass method in ObjectiveC?

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

-(void)didReceiveMemoryWarning { /* do a bunch of stuff */ [super didReceiveMemoryWarning]; } 

against

 -(void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; /* do a bunch of stuff */ } 

same question for other methods like viewWillAppear, willRotateToInterfaceOrientation etc.

I am looking for significant differences, not just stylistic or philosophical (although they are also welcome).

+6
oop ios objective-c iphone cocoa-touch
source share
2 answers

Typical Cocoa convention:

  • If you are tuning, call super FIRST
  • If you do teardown, call super LAST

So, initialization, viewDidLoad, etc. fall under the first case. The memory warnings, viewDidUnload and dealloc relate to the second case.

You must also develop classes to follow this convention. Of particular note are any deviations.

Corresponding SO answer:

`[super viewDidLoad]` agreement


To add: The rationale for calling super during installation is that you want everything to be in place before expanding the functionality. The consequence is that when you absolve yourself of liability, you do not want any subclass ivars of your subclass to depend on being exempted before you can process them.

This makes sense regarding user interface updates as well as in the comments below.

+6
source share

It depends on the functionality, you either want to do something after the superclass has completed its work or earlier.

For example, if a superclass contains some user interface elements, and you extend it, and your class will contain several more user interface elements. To get the size that matches your object, you probably call a superclass to calculate the size of its elements, and then add the size of the added elements to that size.

Otherwise, it does not make sense - the superclass does not know about your elements, so it will overwrite your calculations. Again, this is implementation dependent.

There is a specific case where you need to call the super method as the last:

 -(void)dealloc { ... [super dealloc]; } 
+6
source share

All Articles