如何从其他地方调用Objective-C对象的超类方法?

exe*_*r21 16 iphone cocoa overriding objective-c superclass

如果你正在实现一个子类,你可以在你的实现中显式调用超类的方法,即使你已经覆盖了那个方法,即:

[self overriddenMethod]; //calls the subclass's method
[super overriddenMethod]; //calls the superclass's method
Run Code Online (Sandbox Code Playgroud)

如果你想从子类的实现之外的某个地方调用超类的方法,即:

[[object super] overriddenMethod]; //crashes
Run Code Online (Sandbox Code Playgroud)

这甚至可能吗?而且,通过扩展,是否有可能在实现中超过一个级别,即:

[[super super] overriddenMethod]; //will this work?
Run Code Online (Sandbox Code Playgroud)

Jen*_*ton 22

一个更令人愉快的选择(用于调试)是添加一个类别方法,它为您完成:

- (void) callSuperMethod { [super overriddenMethod]; }
Run Code Online (Sandbox Code Playgroud)

事实上,没有更方便的方法来实现这一点,这在很大程度上取决于设计.


Nic*_*ley 14

[[[object class] superclass] methodForSelector: ...]如果你愿意的话,你可以直接通过IMP指针发送和调用......但是如果你这样做,你的应用程序的设计可能会出现问题.