Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?
like image 646
executor21 Avatar asked May 20 '10 19:05

executor21


People also ask

How to call the superclass method in a subclass?

Subclass methods can call superclass methods if both methods have the same name. From the subclass, reference the method name and superclass name with the @ symbol.

How do you call a superclass method?

To explicitly call the superclass constructor from the subclass constructor, we use super() . It's a special form of the super keyword. super() can be used only inside the subclass constructor and must be the first statement.

Can a subclass object call a superclass method?

Yes, you can call the methods of the superclass from static methods of the subclass (using the object of subclass or the object of the superclass).

What does super mean in Objective C?

Super is self , but when used in a message expression, it means "look for an implementation starting with the superclass's method table."


1 Answers

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.

like image 114
Jens Ayton Avatar answered Sep 21 '22 07:09

Jens Ayton