Objective-c如何在子类中调用父方法中的父方法

时间:2015-02-04 06:22:15

标签: ios objective-c inheritance subclass

@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]。当孩子覆盖方法时,有没有办法在父亲中调用父方法,换句话说,有没有办法选择父方法或子方法。

2 个答案:

答案 0 :(得分:0)

@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 doc https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/WorkingwithObjects/WorkingwithObjects.html

答案 1 :(得分:0)

您可以使用

调用超类方法
[super show]; //call this method from within child class

此方法执行调用show中的Super Class方法(在我们的案例中为父类)

希望这有帮助