[iOS] super.viewDidLoad() 호출하는 이유

2023. 3. 7. 08:27iOS/iOS

728x90
반응형

👉 시작

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}
  • 프로젝트를 처음 생성하면 ViewController 에 ViewDidLoad()는 기본으로 구현되어 있는 메소드이다.

 

 

생명주기 메소드를 작성하다가 호출할 때마다 superClass를 작성하는 것이 자연스럽게 호출하게 되었다.

당연히 슈퍼클래스의 내용을 상속받아 재정의하는 의미라고는 알고 있었지만

까먹고 작성하지 않았을 때가 있었는 데 호출을 하지 않아도 에러가 나지 않았다.

이 부분에서 super.viewDidLoad() 메소드를 호출하는 이유가 궁금해져서 찾아보았다.

 

 


👉 SuperClass (슈퍼클래스) 를 호출하는 이유

일단 결론 먼저 말하자면 호출하지 않아도 무관하지만 호출해주는 것이 좋다!

 

애플 공식 문서에는 

Discussion
Typically, your override would perform one-time instantiation and initialization of the contents of the view controller’s view. If you override this method, call this method on super at some point in your implementation in case a superclass also overrides this method.

ViewDidLoad 메소드를 재정의하는 경우 슈퍼클래스가 ViewDidLoad 메소드를 재정의하는 경우를 대비하여 super 로 호출하십시오. 라고 나와있다.

하지만 반드시 호출하라는 내용이 없다.

호출하지 않아도 컴파일할 때 에러가 나지 않고 앱을 실행할 때도 정상적으로 작동이 된다.

 

예를 들어 UIViewController를 상속받은 커스텀한 ViewController의 viewDidLoad 를 호출할 때

super.viewDidLoad() 를 사용하지 않으면 UIViewController (=슈퍼클래스)의 viewDidLoad() 는 실행되지 않는다.

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        print("ViewController \(#function)")
    }
}

class CustomViewController: ViewController {
    
    override func viewDidLoad() {
//        super.viewDidLoad()
        print("CustomViewController \(#function)")
    }
}

 

스택오버플로우에 따르면
아무 효과가 없더라도 항상 호출해주는 습관을 들이는 것이 좋다고 한다.
호출하는 습관을 들이지 않으면 필요할 때 호출하는 것을 잊을 수 있다.

 

 

 

 

 


📂 정리

슈퍼클래스를 호출하는 것을 습관화하자!

 

 

 

 

 

 

 

 

 

 

[예제 소스코드 깃허브 링크]

https://github.com/HANLeeeee/PracticeTest/tree/main/SuperViewDidLoadTest

 

GitHub - HANLeeeee/PracticeTest

Contribute to HANLeeeee/PracticeTest development by creating an account on GitHub.

github.com

[참고자료]

https://developer.apple.com/documentation/appkit/nsviewcontroller/1434476-viewdidload

 

viewDidLoad() | Apple Developer Documentation

Called after the view controller’s view has been loaded into memory.

developer.apple.com

https://stackoverflow.com/questions/40151723/why-when-do-we-have-to-call-super-viewdidload

 

Why/when do we have to call super.ViewDidLoad?

Everyone tells me "Use super.viewDidLoad() because it's just like that" or "I've been doing it always like that, so keep it", "It's wrong if you don't call super", etc. override func viewDidLoad()...

stackoverflow.com

 

 

 

 

728x90
반응형