【问题标题】:HOWTO access the method declared in the parent class?如何访问父类中声明的方法?
【发布时间】:2011-07-01 02:42:56
【问题描述】:

我想知道是否可以访问在父类中声明的方法,该方法已被覆盖(如果我犯了任何错误,请原谅我的英语)。代码sn-p:

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

所以我的问题是,当 Parent* 指针指向 Child 对象时,如何调用父类中定义的“消息”方法。 Objective-C(纯动态语言)会自动调用 Child 的方法,但是是否可以通过 *p 指针从外部调用父类的方法?我的意思是,当我将消息“消息”发送到“p”时,屏幕上会显示“孩子”而不是“父母”。

谢谢。

【问题讨论】:

    标签: objective-c inheritance methods overriding parent


    【解决方案1】:

    在你的子类的一个类别中,这样写:

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

    【讨论】:

    • 它告诉编译器把对象当作Parent类的一个实例,但是Objective-C是动态语言,所以调用的方法是在运行时确定的,它是子方法被调用。
    【解决方案2】:

    经过几天的学习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;
    }
    

    【讨论】:

      【解决方案3】:

      修改子messgae方法为,

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

      【讨论】:

      • 但这会同时调用父母和孩子的方法。我的目标是只调用父级的“消息”方法,因此屏幕上只会显示“父级”。
      猜你喜欢
      • 2012-12-12
      • 1970-01-01
      • 1970-01-01
      • 2011-06-04
      • 2020-12-24
      • 1970-01-01
      • 2015-08-25
      • 2019-08-07
      • 2018-08-07
      相关资源
      最近更新 更多