Additional Initialization of Nib-Based Instances

By the time a nib finishes loading, its instances are fully fledged; they have been initialized and configured with all the attributes dictated through the Attributes and Size inspectors, and their outlets have been used to set the values of the corresponding instance variables. Nevertheless, you might want to append your own code to the initialization process as an object is instantiated from a loading nib. Most commonly, to do this, you’ll implement awakeFromNib. The awakeFromNib message is sent to all nib-instantiated objects just after they are instantiated by the loading of the nib: at the point where this happens, the object has been initialized and configured and its connections are operational.

For example, our Empty Window app is loading MyNib.xib, extracting a UILabel from it, and inserting that label into our interface; the result is that the words “Hello, world!” appear in our window. Let’s modify the behavior of this UILabel so that it does some additional self-initialization in code. To do that, we will need a class of our own to which our UILabel will belong. Clearly, this needs to be a UILabel subclass. So:

  1. In Xcode, choose File → New → New File and specify that you want a Cocoa Touch Objective-C class. Click Next.
  2. Make the new class a subclass of UILabel. Click Next.
  3. Call it MyLabel. Make sure you’re saving into the project folder; set the Empty Window group and the Empty Window target. Click Save.
  4. In MyLabel.m ...

Get Programming iOS 4 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.