Calling super.init() in initializer of NSObject subclass in Swift

喜你入骨 提交于 2020-01-02 00:48:29

问题


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.



来源:https://stackoverflow.com/questions/25630031/calling-super-init-in-initializer-of-nsobject-subclass-in-swift

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