【问题标题】:Object-c How to call father method in father when being subclassObject-c作为子类时如何在父亲中调用父亲方法
【发布时间】:2015-02-04 06:22:14
【问题描述】:
@interface Father : NSObject
-(void)show;
@end

@interface Child : Father
-(void)show;
@end
- (instancetype)init
{
  self = [super init];
  [self show];
  return self;
}

- (void)show
{
  NSLog(@"I am father");
}
@end

@implementation Child

- (instancetype)init
{
  self = [super init];
  [self show];
  return self;
}

- (void)show
{
  NSLog(@"I am child");
}

@end

- (void)viewDidLoad
{
  Child *child = [[Child alloc] init];
}

Output: 
I am child
I am child

从代码和输出中,我们可以看到父亲中的[self show]实际上调用了[child show]。当方法被子方法覆盖时,有没有办法在父方法中调用父方法,换句话说,有没有办法选择父方法或子方法。

【问题讨论】:

  • 智利班[超级秀];它将运行父类方法。
  • 提示:super。你为什么叫[super init]` ???答案就在那里。
  • @MidhunMP,我认为,OP的意思是他想从基类调用基类实现,即使孩子覆盖它。
  • @MidhunMP,是的,这是一个奇怪的要求,尤其是在 Objective-C 的上下文中(我不确定它是否可能)。这就像在 C++ 中“覆盖”一个非虚拟函数(当你没有真正覆盖它,而只是隐藏父级的实现),当父级调用他自己的实现,而子级调用它自己的实现。
  • @MidhunMP, self 将调用子实现,如果子覆盖它。如果我理解正确,OP 希望调用父级的实现,当他从父级的代码中调用它时,无论如何。

标签: ios objective-c inheritance subclass


【解决方案1】:
@implementation Child

- (instancetype)init
{
  self = [super init];
  [self show];
  return self;
}

- (void)show
{
  NSLog(@"I am child");
  [super show];  // This line call show method of father class
}

@end

- (void)viewDidLoad
{
  Child *child = [[Child alloc] init];
}

试试上面的代码。

浏览 Objective-C 文档https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/WorkingwithObjects/WorkingwithObjects.html

【讨论】:

    【解决方案2】:

    你可以调用超类方法使用

    [super show]; //call this method from within child class
    

    这个方法执行,调用Super Class(本例中的父类)中的show方法

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-22
      • 2017-02-23
      • 1970-01-01
      • 2012-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多