• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

objective-c - 我不明白什么时候需要调用被覆盖的方法,或者它只是不需要。

[复制链接]
菜鸟教程小白 发表于 2022-12-13 09:03:23 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

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

例如,对于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/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap