Objective C 子类重写超类中的方法

发布于 2024-07-17 15:00:07 字数 314 浏览 2 评论 0原文

在 Objective C 中,如果您要子类化某些内容,并计划重写超类上的方法,是否应该在子类 @interface 中重新声明超类方法?

例如,如果您正在子类化 UIViewController(例如 MyViewController),并且您计划重写“viewDidLoad”,您是否应该在 MyViewController @interface 声明中包含该方法,或者只是在 MyViewController.m 中实现它?

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

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?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

静若繁花 2024-07-24 15:00:07

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

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

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.

疯到世界奔溃 2024-07-24 15:00:07

人们经常使用标题作为类的文档(像 AutoDoc 这样的工具支持这一点)。 显然,如果您遵循该约定,唯一明智的选择是包含重新定义的方法,以便您可以解释您使用它们做了什么。 否则,您的课程文档要么不完整,要么分散到地球的四个角落。

但如果我们只是复制粘贴声明,我个人不喜欢重新声明方法。 它不是 DRY 并且它不必要地使您的标头膨胀。 更少的代码就是更好的代码。

People often use the header as documentation for the class (and tools like AutoDoc support this). Obviously, if you're following that convention, the only sensible choice is to include redefined methods so you can explain what you've done with them. Otherwise your docs for the class are either incomplete or scattered to the four corners of the earth.

But if we're just copy-pasting the declaration, I don't personally like to redeclare methods. It's not DRY and it bloats your header unnecessarily. Less code is better code.

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