首页 > 解决方案 > 从 Swift 调用 Objective C 自定义初始化函数

问题描述

A 类是用 Objective C 编写的,并且有一个自定义的 init 函数

@interface A ()

....

@end

@implementation A

- (id)customInitImplementedInA
{
    ... 
    return self;
}

B 类继承自 A 类,并以下列方式使用此自定义初始化:

@interface B : A ()

....

@end

@implementation B
+(instancetype)instanceB{
    B *b = [[B alloc] customInitImplementedInA];
    ...
    return b;
}

现在我想创建一个用Swift编写的 C 类,它继承自 A 并使用相同的 init 函数。我怎么做?

class C: A {
  //How do I use customInitImplementedInA here?
}

标签: iosobjective-cswiftinheritance

解决方案


您应该能够通过super.methodname语法来做到这一点。

class C: A {
    init() {
        super.customInitImplementedInA()
        // Any extra initialization for C goes here.
    }
}

推荐阅读