Differences in adding a subview



First of all may I say a big thankyou for the iPhone book. I’ve been struggling for some time with a number of other sources to learn but your book has clarified a number of issues that I was having. In my opinion, chapter one is probably the most important thing I’ve read and basically made loads of bits pop into place for me. Thanks

Anyway, I’m still learning and as I go through the book and you mention to do something I try to figure it out myself (if it’s already been covered) and type it in before looking at the code in the book. I’ve noticed something in chapters 9 & 10 with regards to adding subviews and I wondered if you could clarify for me.

Chapter 9 P.132

HeavyViewController *hvc = [[HeavyViewController alloc ] init ] ; [window addSubview:[hvc view ]] ;

Chapter 10 P.141

itemsViewController = [[ItemsViewController alloc ] init ] ; [window addSubview:[itemsViewController view] ] ;

with the .h file having the declaration for the pointer to the ItemsViewController:

So, to me these achieve the same thing and I just wanted to clarify that this is the case, or is there some magic that I’ve missed that requires one or the other method to be used?


Right, effectively, the same thing is happening in both of these lines of code. Both chunks of code create an instance of some view controller subclass. Both of them place the view of the view controller into the window’s view hierarchy.

The only difference between these two lines of code is that we keep a pointer to ItemsViewController in the App Delegate. The reason we do this is because later on, you will have the App Delegate send a message to the instance of ItemsViewController. In HeavyViewController example, you don’t keep a pointer to the instance of HeavyViewController because you don’t need to send it messages from the App Delegate later on.


OK, that actually makes sense to me. Things must be sinking in to this head of mine better than I thought.

Many Thanks for taking the time to answer.