为什么在初始化时使用 child class' 实现?

Why is a child class' implementation used when initialising?

创建了两个 classes AB,其中 B subclasses A。尝试初始化 B 时它调用 [super init] 为什么超级 class A 使用 child (B) 的实现printMessage ?

@implementation A

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self printMessage:@"Foo"];
    }
    return self;
}

-(void)printMessage:(NSString *)message
{
    NSLog(@"From A: %@", message);
}

@end

B 的实施(子classes A)

@implementation B

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self printMessage:@"Bar"];
    }
    return self;
}

-(void)printMessage:(NSString *)message
{
    NSLog(@"From B: %@", message);
}

@end

初始化使用:

B *b = [[B alloc] init]

预期输出:

From A: Foo
From B: Bar

实际输出:

From B: Foo
From B: Bar

您正在初始化 B 类型的对象。方法实现的搜索从 class B 开始,如果找到则使用覆盖的方法,否则仅返回父实现。

您的 BprintMessage 必须显式调用 [super printMessage: message] 才能调用它...就像调用 init.


尝试将其放入 Ainit 中以澄清问题:

    NSLog(@"I'm a %@", NSStringFromClass([self class]));