How do you call a method for an Objective-C object's superclass from elsewhere?

六眼飞鱼酱① 提交于 2019-12-06 17:28:00

问题


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?

回答1:


A more pleasant option (for debugging) is to add a category method which does it for you:

- (void) callSuperMethod { [super overriddenMethod]; }

The fact that there’s no more convenient way to do this is very much by design.




回答2:


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.



来源:https://stackoverflow.com/questions/2877251/how-do-you-call-a-method-for-an-objective-c-objects-superclass-from-elsewhere

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!