OGeek|极客世界-中国程序员成长平台

标题: objective-c - 我不明白什么时候需要调用被覆盖的方法,或者它只是不需要。 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 09:03
标题: objective-c - 我不明白什么时候需要调用被覆盖的方法,或者它只是不需要。

我不明白什么时候需要调用被覆盖的方法,或者根本不需要。

例如,对于dealloc,它是必要的

-(void) dealloc
{
   ...
   [super dealloc];
}

我猜也是 init..

-(void) init
{
   [super init];
   ..
}

viewWillAppear 呢?我应该在我的自定义代码之前还是之后调用 super 方法?

(void)viewWillAppearBOOL)animated
{
    [super viewWillAppear:animated];
}

谢谢



Best Answer-推荐答案


确定是否以及何时在重写方法中调用 super 的唯一方法是阅读该方法的文档。

对于您给出的示例: 初始化:The documentation状态:

Subclass versions of init need to incorporate the initialization code for the classes they inherit from, through a message to super: ... Note that the message to super precedes the initialization code added in the method. This sequencing ensures that initialization proceeds in the order of inheritance.

dealloc:The documentation状态:

Subclasses must implement their own versions of dealloc to allow the release of any additional memory consumed by the object—such as dynamically allocated storage for data or object instance variables owned by the deallocated object. After performing the class-specific deallocation, the subclass method should incorporate superclass versions of dealloc through a message to super:

viewWillAppear: The documentation状态:

You can override this method to perform custom tasks associated with presenting the view.
... If you override this method, you must call super at some point in your implementation.

每种方法都不同。如果您覆盖 viewDidAppear: ,您必须调用 super。如果您覆盖 loadView ,您不得。基本上,任何时候你重写一个方法,你都应该检查那个方法的文档,看看你是否应该调用 super,如果是,你应该在你自己的实现之前还是之后这样做。

如果文档没有说明,则由您决定。先把作者的疏忽大骂一顿之后,做你认为有意义的事。如果文档没有说明,我通常倾向于调用 super。

关于objective-c - 我不明白什么时候需要调用被覆盖的方法,或者它只是不需要。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7245021/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4