I know that starting with iOS5 and the new UIViewController containment methods, you are supposed to call these methods together with addChildViewController:, removeFromParentViewController: and the transition method. I also know the proper order of calling them in the three scenarios. What I don't know is what exactly these methods do?
If these were merely override points for subclasses of UIViewController I guess we wouldn't be required to call super when overriding. What can/will go wrong if I don't call willMoveToParentViewController: nil before removing a view controller or didMoveToParentViewController: self?
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.
There are many answers to this:
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.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With