Calling super.init() in initializer of NSObject su

2020-07-02 10:55发布

问题:

I'm building an iOS app in Swift and drawing on the Lister sample project Apple provides.

Lister uses two model objects: List and ListItem. I found that both of them do not call super.init() in their initializers even though they subclass NSObject.

However, in the Objective-C version of Lister, both model objects (AAPLList and AAPLListItem) do call [super init].

The Swift Programming Language clearly states that “designated initializers must call a designated initializer from their immediate superclass.” (Rule 1 of Initializer Chaining in Initialization)

What's going on here? Why is this an exception and if you shouldn't always call super.init() in a subclass, what rules do apply?

回答1:

Even though I can't find a place in the documentation where this is described, what happens is that the default superclass initialiser is called at the end of the subclass initialiser if that is the only initialiser of the superclass, and it wasn't called explicitly.

NSObject only has the default initialiser (init()); you can see that the superclass initialiser is called at the end of the subclass initialiser by attempting to reference self (eg. println(self)) in a constructor that does not call super.init(): You are not allowed to do it because the class is not fully initialised at that point.

If you want to use self somewhere in the constructor, the object needs to be fully constructed at that point, so you need to call super.init() manually before then.