指定的初始化程序应该只在'super'上调用指定的初始化程序当使用协议时?

问题描述:

我有以下结构。 我得到了class B,它符合protocol Aprotocol A定义了一个指定的初始化程序,即-(instancetype)initWithInt:(int)count指定的初始化程序应该只在'super'上调用指定的初始化程序当使用协议时?

但是,当我去执行标准-(instancetype)initclass B并使其使用指定初始化程序,它也在类B中实现,我得到警告“指定的初始化程序应该只调用指定的初始化程序'超' “,而我指定的初始化程序(其中IMO为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; 
} 

任何想法为什么编译器在这种特定情况下省略此警告?

+0

这是什么问题? – matt

+0

@matt刚刚更新了问题部分。 – sramij

+0

你打算如何使用这个协议? – Willeke

Working with Protocols

一类接口声明与该类相关联的方法和属性。相反,协议用于声明独立于任何特定类的方法和属性。

每个类都有自己的(继承)指定初始值设定项。您不能在协议中声明指定的初始化程序。如果你想在一个协议来声明初始化,实现它想:

- (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:

一个指定初始化为特定的一类,并在这个类中声明。您可以初始化类的实例,但不能初始化协议的实例。协议可以在不知道该对象的类的情况下与对象进行交谈。有关初始化程序的文档:Multiple Initializers and the Designated Initializer

+0

你不能在协议中的方法中实现方法,不知道我在这里理解你在说什么。此外,理性地说,在协议中定义一个指定的初始值设定项有什么问题,您的反对意见并不能提供足够的推理。 – sramij

+0

我认为你不明白协议是什么。阅读[使用协议](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/WorkingwithProtocols/WorkingwithProtocols.html)。 – Willeke

+0

为什么选择投票?我应该删除我的答案吗? – Willeke