4

在 Objective-C 中,我应该在方法的顶部还是底部调用超级视图覆盖方法?有什么不同?

例如:

在方法的顶部:

 - (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];
 }

或者在方法的底部:

- (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

3 回答 3

5

在视图生命周期的情况下,您应该首先在方法中调用它,因为您希望超类在您执行所需操作之前完成设置。

尽管在 dealloc 的情况下,您应该在方法结束时调用 super,因为您想在超类清理之前进行清理。

于 2012-08-18T13:40:49.700 回答
0

据我了解,您将其放置在哪里取决于您是否需要在超类方法中完成某些事情,然后再执行您需要在方法中执行的操作。因此,如果有任何工作需要先在 supermethod 中完成,则将 super 调用放在顶部。

于 2012-08-18T13:41:44.877 回答
0

要回答这个问题,您首先需要知道为什么要调用 super。这对于 UIKit 类并不总是很明显,因为您不能轻易地弄清楚这些方法在内部做什么。

然而,忽略这一点,超级调用的位置完全取决于超级类的实现。这里没有黄金法则。有时它应该放在顶部,有时应该放在底部,有时甚至可以在其他行之间调用它。

最佳

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

Bottom

A pretty common case to place it in the bottom would be if you override viewWillAppear: of UITableViewController. UITableViewController internally calls [self.tableView deselectRowAtIndexPath:animated:] in this method to get the little effect of a row selection fading out when you return to the table view from another view. If you need to do something with the selected row before it's automatically deselect, you must place the super call in the bottom (or below the row where you access the selected indexPath).

于 2014-02-12T19:43:56.153 回答