问题
I have the following structure.
I got class B
which conforms to protocol A
.
protocol A
defines a designated initializer which is-(instancetype)initWithInt:(int)count
.
However, when I go an implement the standard -(instancetype)init
in class B
and make it to use the designated initializer which is also implemented in class B, i am getting the warning "Designated initializer should only invoke a designated initializer on 'super'", while my designated initializer (which IMO is initWithInt
) never calls any designated initializer on 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;
}
Any idea why the compiler omits this warning in this specific case?
回答1:
From Working with Protocols:
A class interface declares the methods and properties associated with that class. A protocol, by contrast, is used to declare methods and properties that are independent of any specific class.
Each class has its own (inherited) designated initializer. You can't declare a designated initializer in a protocol. If you want to declare an initializer in a protocol, implement it like:
- (instancetype)initWithInt:(NSUInteger)count {
self = [self initWithMyDesignatedInitializer];
if (self) {
// do something with count
}
return self;
}
or like:
- (instancetype)initWithInt:(NSUInteger)count {
return [self initWithMyDesignatedInitializer:count];
}
And don't declare init
in your protocol, it is declared by NSObject
.
Edit:
It doesn't make sense to declare an initializer in a protocol. When you allocate and initialize the object, you know the class of the object and should call a designated initializer of this class.
Edit 2:
A designated initializer is specific to a class and declared in this class. You can initialize an instance of a class but you can't initialize an instance of a protocol. A protocol makes it possible to talk to an object without knowing the class of this object. Documentation about initializers: Multiple Initializers and the Designated Initializer.
来源:https://stackoverflow.com/questions/46373190/designated-initializer-should-only-invoke-a-designated-initializer-on-super-wh