Loading a NIB File and Sorting Top Objects


So, as a part of my solution to the Mega Gold Challenge, I decided to create a custom view with Interface Builder and then unpack it from the bundle and animate its display on screen when the gesture was recognized. I also needed to get at the three color squares that were a part of the custom view. Now, I know that when you load a nib, you get an array of the top objects in that nib file, but what I don’t understand is how you are supposed to elegantly access each of the top object subviews in the unpacked view.

I figured that since I added the green square first to my custom view, that it was probably going to be topObjects[0], and then the second color square would be [1] and the third [2], but all that seemed very sloppy. Surely there must be a better way at getting at these controls? Does anyone have any sage advice for this, because I’m sure that I will be doing a LOT of packing of custom nib files as I go forward with writing iOS apps.


I wouldn’t recommend looping over the top items and conditionally working with those. Rather, I’d recommend having an IBOutlet to each of the top level objects, similar to what we did with the headerView earlier in the book.

(By the way, the order of the top level objects in the array that gets created from loadNibNamed:owner:options: is the same as their order in the Document Outline in Interface Builder. So in this XIB (cl.ly/image/0f2C1u0K2v45) the array is ordered UIView, UIActivityIndicatorView, UIButton.)


Thanks, Christian! It’s been a while since I read through that chapter, so I’ll go back and study it carefully. I knew that outlets seemed like the way to go; I just couldn’t think of how to make it work. I did try control dragging things to the File’s Owner, but that didn’t work. I may just completely work through the headerView exercise again.


If the dragging doesn’t work, try Control-clicking on “File’s Owner” and dragging the connection from the pop-up menu. I think there is a bug in Xcode 5.1 that causes the normal dragging to not work sometimes.