What exactly willMoveToParentViewController: and didMoveToParentViewController: do?

前端 未结 2 718
傲寒
傲寒 2020-12-24 14:03

I know that starting with iOS5 and the new UIViewController containment methods, you are supposed to call these methods together with addChildViewController:

相关标签:
2条回答
  • 2020-12-24 14:24

    In addition to what has been said, they do call some delegate methods:

    addChildViewController calls [child willMoveToParentViewController:self]

    and removeFromParentViewController: calls [child didMoveToParentViewController:nil]

    Also, they modify the childViewControllers property, which holds an array of child view controllers.

    0 讨论(0)
  • 2020-12-24 14:28

    There are many answers to this:

    1. They are there and you are supposed to call them where applicable to always uphold the pattern. That way, if you change superclasses from UIViewController to your own view controller, you won't have to worry about where you followed the entire pattern.

    2. They are better places to hook into than telling everyone to override addChildViewController:. As you say, mis-managing willMoveToParentViewController: sounds like it's less dangerous than mis-manging addChildViewController:, especially if you forget to call super.

    3. UIViewController probably depends on you upholding the pattern. Maybe it will deem the state inconsistent if it knows that it has received addChildViewController: but never gets the other two messages. Whether this happens due to UIViewController doing book-keeping to lure you into upholding the full pattern or whether you really do mess up its internal state is a fun guessing game, but also something that may change in any iOS release. Things may break badly. That's why the pattern is there, for Apple to tell you that as long as you do this, we will keep things working no matter what.

    Questioning a pattern is good, but there are many potential negatives that come with trying to cut your conformance of a pattern to the bone. Unless the pattern is ridiculously involved, it's usually just easier to conform to it.

    0 讨论(0)
提交回复
热议问题