HOWTO access the method declared in the parent cla

2019-02-19 01:20发布

问题:

I wonder whether it's possible to access a method declared in a parent class, which has been overrided (Sorry for my English if I make any mistakes). The code snippet:

#import <stdio.h>
#import <objc/Object.h>

@interface Parent : Object
-(void) message;
@end

@implementation Parent
-(void) message
{
    printf("\nParent\n");
}
@end

@interface Child : Parent
//-(void) message;
@end

@implementation Child
-(void) message
{
    printf("\nChild\n");
}
@end

int main(int argc, const char* argv[])
{
    Parent* p = [[Child alloc] init];

    [p message];

    [p free];
    return 0;
}

So my question is, how can I call the 'message' method defined in the parent class, when the Parent* pointer points to a Child object. Objective-C (being a pure dynamic language) automatically calls the Child's method, but is it possible to call the method of the parent class from outside, through the *p pointer? I mean, when I send the message 'message' to 'p', not "Child" but "Parent" would be shown on the screen.

Thank you.

回答1:

Modify the child messgae method as,

-(void) message
{
    [super message];
    printf("\nChild\n");
}


回答2:

After days of learning objective-c I've found the solution. This solution explicitly calls the method through function pointer, instead of sending a message. I know this is not a good practice, however I think there are situations when this is necessary to apply. So the code:

#import <stdio.h>
#import <stdlib.h>
#import <Foundation/Foundation.h>

@interface Parent : NSObject     // I switched from Object to NSObject
-(void) message;
@end

@implementation Parent
-(void) message
{
    printf("\nParent\n");
}
@end

@interface Child : Parent
-(void) message;
@end

@implementation Child
-(void) message
{
    printf("\nChild\n");
}
@end

int main(int argc, const char* argv[])
{
    IMP f;
    Parent* p = [[Child alloc] init];  //p could be (Child*) too
    f = [[p superclass] instanceMethodForSelector: @selector(message)];
    f(p, @selector(message));

    [p release];
    return EXIT_SUCCESS;
}


回答3:

In a category on your subclass, write something like this:

-(void)callSuperMessage
{
[super message];
}