Designated initializer should only invoke a designated initializer on 'super' When using protocols?

余生长醉 提交于 2019-12-14 02:34:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!