Categories

A category is an Objective-C language feature that allows you to reach right into an existing class and define additional methods. You can do this even if you don’t have the code for the class, as with Cocoa’s classes. Your instance methods can refer to self, and this will mean the instance to which the message was originally sent, as usual. A category, unlike a subclass, cannot define additional instance variables; it can override methods, but you should probably not take advantage of this ability.

Defining a category is just like defining the class on which the category is being defined: you need an interface section and an implementation section, and you’ll typically distribute them into the standard .h and .m class file pair. At the start of both the interface section and the implementation section, where you give the class’s name, you add a category name in parentheses. The .h file will probably need to import the header for the original class (or the header of the framework that defines it), and the .m file will, as usual, import the .h file, as will any .m file that wants to call one of your additional methods.

The easiest way to set up your .h and .m class file pair as a category is to ask Xcode to do it for you. Choose File → New → File, and in the “Choose a template” dialog, among the iOS Cocoa Touch file types, pick “Objective-C category”. You’ll be asked to give a name for the category and the class on which you’re defining this category.

For example, in one ...

Get Programming iOS 6, 3rd Edition 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.