如何从其他地方调用 Objective-C 对象超类的方法?
如果您正在实现一个子类,您可以在您的实现中显式调用超类的方法,即使您已经覆盖了该方法,即:
[self overriddenMethod]; //calls the subclass's method
[super overriddenMethod]; //calls the superclass's method
如果您想从子类实现之外的某个地方调用超类的方法,即:
[[object super] overriddenMethod]; //crashes
这可能吗?通过扩展,是否有可能在实现中上升不止一个级别,即:
[[super super] overriddenMethod]; //will this work?
If you're implementing a subclass, you can, within your implementation, explicitly call the superclass's method, even if you've overridden that method, i.e.:
[self overriddenMethod]; //calls the subclass's method
[super overriddenMethod]; //calls the superclass's method
What if you want to call the superclass's method from somewhere outside the subclass's implementation, i.e.:
[[object super] overriddenMethod]; //crashes
Is this even possible? And by extension, is it possible to go up more than one level within the implementation, i.e.:
[[super super] overriddenMethod]; //will this work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一个更令人愉快的选择(用于调试)是添加一个为您执行此操作的类别方法:
事实上,没有更方便的方法来执行此操作,这很大程度上是设计使然。
A more pleasant option (for debugging) is to add a category method which does it for you:
The fact that there’s no more convenient way to do this is very much by design.
如果您愿意,您可以发送
[[[object class] superclass] methodForSelector: ...]
并直接通过 IMP 指针调用...但如果您这样做,可能会出现一些非常严重的情况您的应用程序的设计有问题。You can send
[[[object class] superclass] methodForSelector: ...]
and invoke through the IMP pointer directly, if you want... but if you're doing this, there's probably something very wrong with your application's design.