覆盖超类中方法的Objective C子类 [英] Objective C subclass that overrides a method in the superclass

查看:103
本文介绍了覆盖超类中方法的Objective C子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在目标C中,如果您要继承某些东西,并打算重写超类上的方法,则是否应该在子类@interface中重新声明超类方法?

In Objective C, if you are subclassing something, and are planning to override a method on the superclass, should you re-declare the superclass method in your subclass @interface?

例如,如果您要继承UIViewController(例如MyViewController),并且打算覆盖"viewDidLoad",则应在MyViewController @interface声明中包含该方法,还是仅在MyViewController.m中实现该方法?

For example, if you are subclassing UIViewController (e.g. MyViewController), and you are planning to override "viewDidLoad" should you include that method in your MyViewController @interface declaration, or just implement it in MyViewController.m?

在我遇到的示例中,我已经看到它完成了两种方式(在子类接口中重新声明该方法,或者不重新声明该方法).功能上可能没有任何区别,但是最佳实践是什么?

In examples I've come across, I've seen it done both ways (re-declaring the method in your subclass interface, or not re-declaring the method). There may not be any functional difference, but what is the best practice?

推荐答案

我经常在公共标头或至少在私有类别中声明要覆盖的方法.这样做的好处是,如果您忘记实际覆盖该方法,则会收到不完整的类定义警告……有时会派上用场.

I often declare methods that I plan to override in either the public header or at least in a private category. The benefit to this is that you'll get an incomplete class definition warning if you forget to actually override the method... which comes in handy from time to time.

关于何时将其放置在公共标题中,这是非常主观的,可能取决于您/您的团队的编码风格.通常,仅当我计划从根本上更改该方法将要执行的操作或计划不调用该方法的超类版本时,才在公共标头中重新声明该方法.

As for when to place it in the public header, that's pretty subjective and probably up to you/your team's coding styles. I usually only redeclare a method in the public header if I plan to radically change what the method is going to do or if I plan not to invoke the super class's version of the method.

这篇关于覆盖超类中方法的Objective C子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆