问题
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?
回答1:
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.
回答2:
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-managingwillMoveToParentViewController:
sounds like it's less dangerous than mis-mangingaddChildViewController:
, especially if you forget to callsuper
.UIViewController
probably depends on you upholding the pattern. Maybe it will deem the state inconsistent if it knows that it has receivedaddChildViewController:
but never gets the other two messages. Whether this happens due toUIViewController
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.
来源:https://stackoverflow.com/questions/12909788/what-exactly-willmovetoparentviewcontroller-and-didmovetoparentviewcontroller