在对iOS ViewController进行编程时,应该在自己的代码之前还是之后调用父类方法?

编程入门 行业动态 更新时间:2024-10-24 22:28:01
本文介绍了在对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进行编程时,应该在自己的代码之前还是之后调用父类方法?

本文发布于:2023-10-27 11:39:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1533248.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自己的   在对   代码   方法   ViewController

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!