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

发布于 2024-09-25 03:08:54 字数 414 浏览 3 评论 0原文

从模板创建的新 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

看轻我的陪伴 2024-10-02 03:08:54

这一般适用于所有 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.

青瓷清茶倾城歌 2024-10-02 03:08:54

在 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文