なんとかするから、なんとかなる

エンジニア関係のことを書きます

iOSでViewControllerのライフサイクルでsuperを呼ぶべき?呼ばなくても良い?

背景

iOSの開発をしていると必ず必要となるViewController。

ViewControllerにはライフサイクルがあります。

ここまでは、普通の話ですがライフサイクル中のメソッドviewDidLoadなどで

親クラスのメソッドsuperを呼び忘れることがあります。その場合大丈夫なのだろうか。公式ドキュメントで調べてみました。

viewDidLoad

記載がないため呼ばなくてもよい?

viewWillAppear(_:)

必ずsuper呼ぶ必要があります。

 If you override this method, you must call super at some point in your implementation. 

viewWillLayoutSubviews()

デフォルト実装はないので、superは呼ばなくて良いようです。

The default implementation of this method does nothing.

viewDidLayoutSubviews()

デフォルト実装はないので、superは呼ばなくて良いようです。

The default implementation of this method does nothing.

viewDidAppear(_:)

必ずsuper呼ぶ必要があります。

 If you override this method, you must call super at some point in your implementation. 

updateViewConstraints()

必ずsuper呼ぶ必要があります。しかも最後に呼べと記載されています

Call [super updateViewConstraints] as the final step in your implementation.

viewWillDisappear(_:)

必ずsuper呼ぶ必要があります。

 If you override this method, you must call super at some point in your implementation. 

viewDidDisappear(_:)

必ずsuper呼ぶ必要があります。

 If you override this method, you must call super at some point in your implementation. 

最後に

viewDidLoadはデフォルト実装でsuperを読んでいるので、必須と思いきやその記載がないのは意外でした。

その他のメソッドについては、Viewのframeなどがどのように決定するのかがわかっていると、まぁ呼ぶべきだよねって感じですね。

参考URL

もちろん公式ドキュメントです。

https://developer.apple.com/documentation/uikit/uiviewcontroller