Objective-C Upper or lower supercall in overridden method

In objective-C, should I call the super-look redefinition method at the top or bottom of the method? What is the difference?

For instance:

At the top of the method:

- (void)viewDidLoad { // HERE [super viewDidLoad]; //Init the table view UITableView *aTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 100, 400)]; aTableView.delegate = self; aTableView.dataSource = self; aTableView.backgroundColor = [UIColor clearColor]; self.tableView = aTableView; [aTableView release]; } 

Or at the bottom of the method:

 - (void)viewDidLoad { //Init the table view UITableView *aTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 100, 400)]; aTableView.delegate = self; aTableView.dataSource = self; aTableView.backgroundColor = [UIColor clearColor]; self.tableView = aTableView; [aTableView release]; // HERE [super viewDidLoad]; } 
+4
source share
3 answers

In the case of the view life cycle, you must first call it in the method, because you want the superclass to complete the setup before doing what you need.

Although in the case of dealloc you should call super at the end of the method, because you want to clear before the superclass is cleared.

+4
source

As I understand it, the place where you post it will depend on whether you need things done in the superclass method before doing what you need to do in your method. Therefore, if there is any work that needs to be done first in the super method, then the super call will be placed at the top.

0
source

To answer this question, you need to know why you call super in the first place. This is not always obvious with UIKit classes, since you cannot easily understand what the methods inside do.

Ignoring that, however, the placement of supercalls depends entirely on what the implementation of the superclass does. There is no golden rule. Sometimes it must go from above, sometimes from below, and sometimes even call it between other lines.

Top

An example of when it should be placed at the top is that you must override the loadView method of the loadView to add some subzones to its view. In this case, the implementation of the superclass loads the actual view on which you should place the subviews, so placing it at the top is the right way (or it won't work at all).

From below

A fairly common case to put it at the bottom is if you override viewWillAppear: of UITableViewController . The UITableViewController internally calls [self.tableView deselectRowAtIndexPath:animated:] in this method to get a slight effect on row selection when you return to a table view from another view. If you need to do something with the selected row, before you automatically deselect, you must place the super call at the bottom (or below the row where you access the selected indexPath).

0
source

All Articles