重写方法中的Objective-C顶部或底部超级调用
在objective-C中,我应该在方法的顶部还是底部调用super view override方法?有什么区别 例如: 在方法的顶部:重写方法中的Objective-C顶部或底部超级调用,objective-c,ios,Objective C,Ios,在objective-C中,我应该在方法的顶部还是底部调用super view override方法?有什么区别 例如: 在方法的顶部: - (void)viewDidLoad { // HERE [super viewDidLoad]; //Init the table view UITableView *aTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 100, 400)];
- (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];
}
或者在方法的底部:
- (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];
}
在视图生命周期的情况下,您应该首先在方法中调用它,因为您希望超类在您执行所需操作之前完成设置
尽管在dealloc的情况下,您应该在方法的末尾调用super,因为您希望在超类清理之前进行清理。据我所知,将其放置在何处取决于您是否需要在超类方法中完成操作,然后再在方法中执行需要执行的操作。因此,如果在supermethod中有任何工作需要首先完成,那么请将super call放在顶部。要回答这个问题,您需要知道为什么要首先调用super。这在UIKit类中并不总是显而易见的,因为您无法轻松了解这些方法在内部的作用 但是,忽略这一点,超级调用的位置完全取决于超级类实现的功能。这里有一条非黄金法则。有时它应该在顶部,有时在底部,有时甚至可以在其他行之间调用它 顶部 关于何时应将其放置在顶部的示例是,您是否要覆盖
UIViewController
的loadView
方法,以将一些子视图添加到其视图中。在这种情况下,超类实现加载您应该放置子视图的实际视图,因此将其放置在顶部是正确的方法(否则它根本不起作用)
底部
将其放在底部的一种非常常见的情况是,如果您覆盖viewwillbeen:
的UITableViewController
。UITableViewController在此方法中内部调用[self.tableView取消行索引路径:animated:
,以在您从另一个视图返回表视图时获得行选择淡出的小效果。如果需要在自动取消选择选定行之前对其执行某些操作,则必须将超级调用放在底部(或访问选定行的行下方)