Pergunta

I found some info of the designated initializer in this Apple's docs, but what I don't understand is, must each class have one and only one designated initializer?

For example, what if class A has initL, initM, initN, while class B inherits from class A and has initX, initY, initZ. Is there a rule that says we can't have initX call [super initL], and initY call [super initM], and initZ call [super initN]?

That is, instead of all "secondary initializers" call the designated initializer, and then each designated initializer will call the [super initFoo] where initFoo is the superclass's designated initializer, can't we just have 3 primary initializers, and each one caller its corresponding superclass's 3 primary initializers? (and say, these all inherit from NSObject and just call self = [super init].)

Foi útil?

Solução

No, an obj-c class may have multiple designated initializers. The most common example of this is -initWithCoder: vs -init. The former is used when unarchiving an object, and the latter is used for all other initialization.

That said, it's generally good practice to only have one designated initializer outside of -initWithCoder:. This helps to prevent code duplication and makes it obvious which method a subclass has to override if they want to be invoked for all initializations. But if you have a good case for needing 3 distinct designated initializers, then there's nothing stopping you from doing it. Just be sure to document it properly.

Outras dicas

Designated initializers are a concept that helps to prevent recursive calls and omitted important base class initialization. It is possible to not follow the designated initializer rules and still build a working class hierarchy.

In fact there are patterns in Cocoa that deviate from pure designated initializes: NSCoding for example requires to initialze objects using initWithCoder: but you can still initialize objects from code using the other initializers.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top