Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly willMoveToParentViewController: and didMoveToParentViewController: do?

Tags:

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?

like image 215
konrad Avatar asked Oct 16 '12 07:10

konrad


2 Answers

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.

like image 62
Guillaume Avatar answered Sep 30 '22 01:09

Guillaume


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.

like image 24
Jesper Avatar answered Sep 30 '22 01:09

Jesper