This puzzles me to no end.
Say you do:
[self.view addSubview: someController.view];
How does someController knows that it’s view is being loaded and call viewDidAppear, etc.?
What we are passing is it’s view and not the controller. Yet someController knows.
Also what happen if self.view itself is not in the window’s view Hierarchy. Will someController’s viewWillAppear, etc. be called?
One way to implement this is to have the view to have a weak pointer to the controller, say as it’s delegate, and then check if the view itself is a descendant of the window object.
Is this the way it’s actually implemented? If not, how it’s actually done? Even if it’s not, is it correct to think that it’s implemented that way?
My concern is the following:
I am curious because I want to understand how this viewWillAppear show up. Months I played with IOS calling those explicitly not knowing why it’s called or not called. There are tons of posts complaining about viewWillAppear/Disapear get called or not called. Some get called twice. I want to know exactly how and when it’s called. I am getting good at it but not quite there yet.
I’ve never seen the UIKit source code, but I’m certain it is as you suspect, and that UIView has a private reference to the UIViewController. This is confirmed by the documentation for UIResponder. Since both UIView and UIViewController participate in the responder chain, you can get a reference to the controller from the view by calling the view’s
nextRespondermethod (emphasis mine):As for your other question: I don’t think
viewWillAppear:will be called unless the view is actually going to appear; in other words, not unless the view is in the window’s view hierarchy. (You could easily write a quick demo project to test this.)