How do you call a method for an Objective-C object

2019-04-18 13:50发布

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?

2条回答
The star\"
2楼-- · 2019-04-18 14:25

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.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-04-18 14:33

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.

查看更多
登录 后发表回答