HOWTO access to a method declared in the parent class?

I wonder if it is possible to access a method declared in a parent class that has been overridden (sorry for my English if I am wrong). 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 name the message method defined in the parent class when the Parent * pointer points to a Child object. Objective-C (which is a pure dynamic language) automatically calls the Child method, but is it possible to call the method of the parent class from the outside, through a * p-pointer? I mean when I send the message "message" to "p" and not "Child", but "Parent" will be displayed on the screen.

Thank.

+3
source share
3

objective-c . . , , , , . , :

#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;
}
+2

child messgae as,

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

In the category of your subclass, write something like this:

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

Source: https://habr.com/ru/post/1793531/


All Articles