Categories and protocols (iOS 4)

It’s important to touch on two final elements of Objective-C: the category and the protocol. We broadly define what they do, but we won’t delve too deeply into their details.

The category

Categories are used if you want to add behavior to a class without subclassing. As usual, you do so by creating a new pair of files containing @interface and (implementation code. This time, you no longer need to worry about the superclass name but must include a category name in parentheses, as follows:

tmp1241_thumb

As a result, the categorized methods and variables that you describe for the classes are added to the core class definition in your program. We don’t use categories in this topic.

The protocol

A protocol is effectively an interface that’s not tied to a class. It declares a set of methods, listing their arguments and their returns. Classes can then state that they’re using the protocol in their own @interface statements. For example, if you had a Growing protocol that was used by plants and animals alike, you could define its usage as follows:


tmp1242_thumb

The AppleTree class would be promising that it would respond to all the methods defined in the Growing protocol.

You won’t be creating any new protocols in this topic. But you’ll use existing ones, because within Apple’s iOS, they’re tied integrally to the MVC model. Views hand off protocol descriptions of how they should be used to view controllers via datasource and delegate properties—both topics that we’ll introduce when we talk about iOS.

With that, the shine has gone off our apples, so we’ll return to real-life examples when we move on. But first, having provided an overview of a whole new programming language in an impossibly short number of pages, we’ll summarize what you’ve learned.

Next post:

Previous post: