我有以下结构。我得到了符合class B的protocol A。protocol A定义了一个指定的初始化器,即-(instancetype)initWithInt:(int)count。
但是,当我在class B中实现标准初始化器并使其使用也在B类中实现的指定初始化器时,我将收到警告:“指定的初始化程序只应在‘class B’上调用指定的初始化器”,而我的指定初始化器(它是initWithInt)从未在Super上调用任何指定的初始化器。
@protocol A
{
(instancetype) init;
(instancetype) initWithInt:(NSUInteger)count;
}
@interface B : NSObject <A>
@implementation B
- (instancetype) init {
return [self initWithInt:0];
}
- (instancetype) initWithInt:(NSUInteger)count {
self = [super init];
return self;
}知道为什么编译器在这种特殊情况下省略此警告吗?
发布于 2017-09-23 10:34:57
来自使用协议
类接口声明与该类关联的方法和属性。相反,协议用于声明独立于任何特定类的方法和属性。
每个类都有自己的(继承)指定的初始化器。您不能在协议中声明指定的初始化器。如果要在协议中声明初始化器,请将其实现如下:
- (instancetype)initWithInt:(NSUInteger)count {
self = [self initWithMyDesignatedInitializer];
if (self) {
// do something with count
}
return self;
}或者说:
- (instancetype)initWithInt:(NSUInteger)count {
return [self initWithMyDesignatedInitializer:count];
}不要在协议中声明init,它是由NSObject声明的。
编辑:
在协议中声明初始化程序是没有意义的。当您分配和初始化对象时,您知道对象的类,并且应该调用该类的指定初始化器。
编辑2:
指定的初始化程序特定于类,并在该类中声明。可以初始化类的实例,但不能初始化协议的实例。协议使得可以在不知道对象的类的情况下与对象进行对话。关于初始化器的文档:多个初始化器和指定的初始化程序。
https://stackoverflow.com/questions/46373190
复制相似问题