tags:

views:

28

answers:

2

In Objective-C, I have a base class A, with instance method -(void) doSomething. Class B is derived from A and overwrites doSomething. Class C is derived from B. In the implementation of C's doSomething, I want to invoke A's doSomething (instead of B's). How do I achieve this? I know I can use [super doSomething] to invoke the immediate super-class implementation, but what if I need a more basic implementation higher above in the inheritance tree, like in the case mentioned above. In C++ you would simply do the following:

void C::doSomething()  
{  
    A::doSomething();  
}

How do I achieve the same thing in Objective-C?

A: 

You can't do that in Objective-C, and the desire to jump around the class hierarchy that way is symptomatic of a serious design flaw.

jlehr
Thank you for confirming this limitation, so I won't waste any more time searching for a way to mimic the C++ style. Actually, this is not a design flaw, but facilitates DRY design. At least true for C++ and virtual functions. You will see such design practice in many OO frameworks, for example MFC.
Arasch
+1  A: 

You can extract the code into a static method which takes an instance as an argument. Example:

@interface A : NSObject
{
}

+(void)joe_impl:(A*)inst;

-(void)joe;

@end

@implementation A
+(void)joe_impl:(A*)inst{
    NSLog(@"joe: A");
}

-(void)joe{
    [A joe_impl:self];
}
@end
@interface B : A
{
}

-(void)joe;

@end

@implementation B

-(void)joe{
    [super joe];
    NSLog(@"joe:B");
}
@end
@interface C : B
{
}

-(void)joe;

@end

@implementation C

-(void)joe{
    [A joe_impl:self];
    NSLog(@"joe:C");
}
@end
Maz
Thanks for your reply. I will do it this way. I thought there might be a "cleaner" way in terms of object-oriented programming. You would never do this in C++, i.e. write a static member function that expects a this pointer ;-)
Arasch