本文介绍了指定初始化器应该只在“超级"上调用指定初始化器 使用协议时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下结构.我得到了符合 protocol Aclass B.protocol A 定义了一个指定的初始化器,它是-(instancetype)initWithInt:(int)count.

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.

但是,当我在 class B 中实现标准的 -(instancetype)init 并使其使用也在 class B 中实现的指定初始化程序时,我收到警告指定的初始化程序应该只在 'super' 上调用指定的初始化程序",而我的指定初始化程序(IMO 是 initWithInt)从不调用 super 上的任何指定的初始化程序.

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?

推荐答案

来自 使用协议:

类接口声明与该类关联的方法和属性.相比之下,协议用于声明独立于任何特定类的方法和属性.

每个类都有自己(继承的)指定的初始化程序.您不能在协议中声明指定的初始化程序.如果要在协议中声明初始化程序,请按如下方式实现:

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;
}

或喜欢:

- (instancetype)initWithInt:(NSUInteger)count {
    return [self initWithMyDesignatedInitializer:count];
}

并且不要在你的协议中声明init,它是由NSObject声明的.

And don't declare init in your protocol, it is declared by NSObject.

在协议中声明初始化器是没有意义的.当你分配和初始化对象时,你知道对象的类,应该调用这个类的指定初始化器.

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.

编辑 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.

这篇关于指定初始化器应该只在“超级"上调用指定初始化器 使用协议时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 15:12