【问题标题】:No visible @interface for custom constructor自定义构造函数没有可见的@interface
【发布时间】:2018-11-05 00:51:34
【问题描述】:

我试图编写一个看起来像这样的自定义初始化程序:

 - (id) initWithTitle:(NSString *) title withDescription:(NSString *) desc {
    self = [super initWithTitle: title withDescription: desc];
    if (self) {
        self.title = title;
        description = desc;
        duration = 0.0;
        priority = 0;
    }
    return self;
}

但由于某种原因,如果我使用 [super initWithTitle: title withDescription: desc],它会告诉我没有可见的 @interface for 'NSObject' 声明了我的选择器,尽管我已经在 .h 文件中定义了构造函数。

我可以只使用 [super init],但我只是想知道我在未来做错了什么。

【问题讨论】:

    标签: ios objective-c constructor interface header


    【解决方案1】:

    行:

    self = [super initWithTitle: title withDescription: desc];
    

    通过调用它的超级构造函数来初始化一个对象。但是,如果超类不包含您要调用的构造函数,则会显示错误消息。

    将您的呼叫替换为[super init],然后在init 上使用Command + Click 以打开NSObject.h,您将看到仅支持init

    【讨论】:

    • 哦。这就说得通了。所以如果我想用自定义的 initWithTitle:withDescription: 来初始化我的类,我会做 [self initWithTitle:withDescription] 吗?
    • 不,如果initWithTitle:withDescription: 是你的类构造函数,那是不正确的。 self 在构造函数被调用之前是nil,所以像[self initWithTitle:withDescription:] 这样的调用会导致编译错误。正确的做法是调用super类的构造函数。
    • 哦,好的。我想我现在明白了。感谢您的回复!
    • 不客气。但是,如果它有助于解决您的问题,请不要忘记在答案中添加复选标记。这将帮助未来面临同样情况的人。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多