shakthi
shakthi

Reputation: 1657

In Objective-C, How one can forward method to specific super class

All I knew is this: Objective-c allows us to forward method invocation to its super class by [super method] However I want forward the invocation to super.super; Skipping the immediately super class.

In c++ we can easily do these by typecasting ((GrandSuper*)object).method().

Is their any provision to do the same in objective c

Upvotes: 0

Views: 1107

Answers (3)

Sean McGuffee
Sean McGuffee

Reputation: 9

I think you can also just call the super of the super:

[[[self super] super]functionOfInterest];

Upvotes: 0

kennytm
kennytm

Reputation: 523484

I think you need to use objc_msgSendSuper directly, i.e.

#include <objc/message.h>
...

struct objc_super theSuper = {self, [GrandSuper class]};
id res = objc_msgSendSuper(&theSuper, @selector(method));

Upvotes: 3

Tom Dalling
Tom Dalling

Reputation: 24145

It's probably a bad idea to do this, although it is possible. You probably want to think of a better way to achieve whatever you're trying to do.

Let's assume that you have three classes: Cat which inherits from Mammal which inherits from Animal.

If you are in the method -[Cat makeNoise], you can skip -[Mammal makeNoise] and call -[Animal makeNoise] like so:

-(void) makeNoise;
{
    void(*animalMakeNoiseImp)(id,SEL) = [Animal instanceMethodForSelector:@selector(makeNoise)];
    animalMakeNoiseImp(self, _cmd);
}

Upvotes: 3

Related Questions