开发者

Objective-C: Calling non-immediate base class implementation from within derived class

开发者 https://www.devze.com 2023-01-08 04:34 出处:网络
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 doSometh

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 doSometh开发者_JAVA技巧ing] 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?


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


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.


You may use [super doSomething] for calling superclass methods

0

精彩评论

暂无评论...
验证码 换一张
取 消