在编写 iOS ViewController 时,您应该在自己的代码之前还是之后调用父类方法?
从模板创建的新 iOS ViewController 包含多个调用其父类方法的“样板”方法。
-(void) viewDidLoad {
[super viewDidLoad];
}
- (void) viewDidUnload {
[super viewDidUnload];
}
- (void) dealloc {
[super dealloc];
}
修改这些类时,我应该把自己的代码放在父类调用之前还是之后?
- (void) viewDidLoad {
// Should I put my code here?
[super viewDidLoad];
// Or here?
}
A new iOS ViewControllers created from a template contains several "boilerplate" methods that call their parent class methods.
-(void) viewDidLoad {
[super viewDidLoad];
}
- (void) viewDidUnload {
[super viewDidUnload];
}
- (void) dealloc {
[super dealloc];
}
When modify these classes, should I put my own code before or after the parent class calls?
- (void) viewDidLoad {
// Should I put my code here?
[super viewDidLoad];
// Or here?
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这一般适用于所有 OOP。在构造函数(以及其他方法)中,您应该在代码之前调用父级的构造函数。原因是您的代码可能需要一些在父类中处理的初始化,即基类的初始化应该在派生类的初始化之前进行。在析构函数中,您应该做相反的事情,即释放派生类的资源应该在释放基类的资源之前。原因很简单。派生类的资源可能依赖于基类的资源。如果你之前释放了基地的资源,那么可能会出现麻烦。
这是理想的情况。在许多情况下,您可能看不到任何区别,但如果存在如上所述的依赖性,那么您就会遇到麻烦。因此,您应该遵循标准,在代码之前调用基类的方法,并在 dealloc 中执行相反的操作。
This is applicable for all OOP in general. In constructor (and in other methods too) you should call the parent's constructor before your code. The reason is your code may require some initialization which are handled in parent, i.e. initialization of base should go before initialization of derived class. In destructor you should do the opposite, i.e. releasing of derived class's resources should go before releasing resources of base. The reason is straight forward. Derived class's resource may depend on base's resource. If you release resource of base before then there might be trouble.
This is the ideal case. In many cases you may see no difference but if there is dependency like described above then you will be in trouble. So you should follow the standard, call base class's method before your code and in dealloc do the opposite.
在 viewDidLoad (通常)中,您应该在之后执行,因为它调用父类上的 load 方法
在 dealloc 中,您应该在之前执行
In viewDidLoad (and generally) you should go after, cause its calling the load method on the parent class
In dealloc you'd go before