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

天涯浪子 提交于 2020-03-16 02:38:00

问题


In UIViewController's documentation, Apple suggests calling the super at some point in the implementation of viewWillAppear, viewDidAppear, viewWillDisappear, viewDidDisappear, etc... For example, the discussion on viewDidDisappear is:

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.

My question is does it matter when the super method is called and, if so, what is the correct time to call it? Should super be called as the first line of the method, the last line, or somewhere in the middle depending on your particular needs?


回答1:


In viewDidAppear call super first so that your calls will override.

In viewWillDisappear it seems to be a toss up, I have researched that extensively and could not find a conclusive answer and it seems to be 50/50. I have decided to call super last in my code in the same manner we call super last in dealloc.




回答2:


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)
}



回答3:


I generally will call these first within my implementation. In most cases it shouldn't matter though.



来源:https://stackoverflow.com/questions/7614841/when-do-you-call-the-super-method-in-viewwillappear-viewdiddisappear-etc

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