在对iOS ViewController进行编程时,应该在自己的代码之前还是之后调用父类方法? [英] When programming iOS ViewControllers should you call parent class methods before or after your own code?

查看:34
本文介绍了在对iOS ViewController进行编程时,应该在自己的代码之前还是之后调用父类方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从模板创建的新的iOS ViewControllers包含几个调用其父类方法的样板"方法.

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?
}

推荐答案

这通常适用于所有OOP.在构造函数中(以及在其他方法中),您应该在代码之前调用父对象的构造函数.原因是您的代码可能需要一些初始化工作,这些初始化工作需要在父对象中进行处理,即基类的初始化应在派生类的初始化之前进行.在析构函数中,您应该做相反的事情,即释放派生类的资源应该先释放基类的资源.原因很简单.派生类的资源可能取决于基础资源.如果您在此之前释放基础资源,则可能会遇到麻烦.

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.

这是理想的情况.在许多情况下,您可能看不到任何区别,但是如果存在如上所述的依赖关系,则会遇到麻烦.因此,您应该遵循标准,在代码之前和dealloc中执行相反的操作,调用基类的方法.

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.

这篇关于在对iOS ViewController进行编程时,应该在自己的代码之前还是之后调用父类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆