Home / iPhone Tips and Tutorials

Framework Classes

Although you will be creating classes of your own (especially model classes), often you will want to customize the behavior of framework class. There are two ways to go about it:

  • Subclassing
  • Delegating

Subclassing

Objective-C, like other object-oriented programming languages, permits you to base a new class definition on a class already defined. The base class is called a superclass; the new class is its subclass. The subclass is defined only by its extension to its superclass; everything else remains the same. Each new class that you define inherits methods and instance variables of its superclass.

Some framework classes are expected to be subclassed. Among them are view controllers, and you will be subclassing quite a bit. Others are not expected to be subclassed, but because of the need to customize their behavior, you use delegation instead.

The Delegation pattern

Delegation is a pattern used extensively in the iOS frameworks, so much so that clearly understanding it is very important. In fact, when you understand it, your life will be much easier.

Delegation, as mention in the previous section, is a way of customizing the behavior of an object without subclassing it. Instead, one object (a framework or any other object) delegates the task of implementing one of its responsibilities to another object. You're using a behavior-rich object supplied by the framework as is, and putting the code for program-specific behavior in a separate (delegate) object. When a request is made of the framework object, the method of the delegate that implements the programspecific behavior is automatically called.

For example, the UIApplication object handles most of the actual work needed to run the application. But, as you saw, it sends your application delegate the application:didFinishLaunchingWithOptions: message to give you an opportunity to create (model) objects that are unique to your app.

When a framework object has been designed to use delegates to implement certain behaviors, the behaviors it requires (or gives you the option to implement) are defined in a protocol.

Protocols define an interface that the delegate object implements. On the iPhone, protocols can be formal or informal, although I concentrate solely on the former because formal protocols include support for things like type checking and runtime checking to see whether an object conforms to the protocol.

In a formal protocol, you usually don't have to implement all the methods; many are declared optional, meaning that you have to implement only the ones relevant to your app. Before a formal protocol attempts to send a message to its delegate, the host object determines whether the delegate implements the method (via a respondsToSelector: message) to avoid the embarrassment of branching into nowhere if the method is not implemented.

[Previous] [Contents] [Next]