When do you call the super method in viewWillAppear, viewDidDisappear, etc…?

前端 未结 3 1199
我在风中等你
我在风中等你 2021-01-12 01:57

In UIViewController\'s documentation, Apple suggests calling the super at some point in the implementation of viewWillAppear, viewDidAppear, viewWillDisappear, viewDidDisapp

3条回答
  •  有刺的猬
    2021-01-12 02:10

    For UIViewController's view life cycle methods, I'd say that there is no silver bullet rule for determining when to call super, what you should be aware of is that sometimes you must call it regardless of whether it should be at the begging or at the end of the method. For instance, citing from viewDidDisappear(_:):

    You can override this method to perform additional tasks associated with dismissing or hiding the view. If you override this method, you must call super at some point in your implementation.

    However, as a general practice we usually call the super method at the beginning in methods that related to initialization, setup or configurations; On the other hand, we usually call the super method at the end in methods related to deinitialization or similar methods.

    Here is an example of XCTestCase class's invocation methods:

    override func setUp() {
        super.setUp()
        // do the setups, such as creating the mock objects...
    }
    
    override func tearDown() {
        // make your objects no be nil for the next test...
        super.tearDown()
    }
    

    So (as another example), when it comes to the viewWillAppear and viewDidDisappear methods:

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // my code...
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        // my code
        super.viewDidDisappear(animated)
    }
    

提交回复
热议问题