本文介绍了调用超类的方法的时机在ObjectiveC中是否重要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

重要的是,如果我调用超类的方法第一件事还是结束?例如

Does it matter if I call the method of the super class first thing or at the end? For example

-(void)didReceiveMemoryWarning {
   /* do a bunch of stuff */

   [super didReceiveMemoryWarning];
}

对比

-(void)didReceiveMemoryWarning {
   [super didReceiveMemoryWarning];

   /* do a bunch of stuff */
}

我正在寻找有意义的差异,不仅仅是风格或哲学(尽管这些也是受欢迎的)。

I am looking for meaningful differences, not just stylistic, or philosophical (although those are welcome too).

推荐答案

典型的可可规则:


  1. 您正在执行设置,请调用
    super FIRST

  2. 如果您正在执行
    teardown,请调用super LAST

所以,初始化,viewDidLoad等都属于第一种情况。内存警告,viewDidUnload和dealloc属于第二种情况。

So, initialization, viewDidLoad, etc.. fall under the first case. Memory warnings, viewDidUnload, and dealloc fall under the second case.

你还应该设计你的类遵循这个约定。

You should also design your classes to follow this convention. Any deviations should be specifically noted.

相关SO答案:

要添加:
在安装过程中调用super的理由是,你想确保在扩展功能之前一切都已经到位。推论是,当你解除分配时,你不想要任何超类ivars,你的子类依赖于在你有机会处理它们之前被解散。

To add:The rationale for calling super first during setup, is that you want to make sure everything is in place before you extend functionality. The corollary, is that when you are deallocating, you don't want any superclass ivars your subclass depends on to be dealloced before you have a chance to handle them.

对于UI更新以及在下面的注释中都有说明。

This makes sense in reference to UI updates as well as noted in the comments below.

这篇关于调用超类的方法的时机在ObjectiveC中是否重要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 20:09