You can use categories to extend classes defined by other implementors—for example, you can add methods to the classes defined in the Cocoa frameworks. The added methods are inherited by subclasses and are indistinguishable at runtime from the original methods of the class.
A category can be an alternative to a subclass. Rather than define a subclass to extend an existing class, through a category you can add methods to the class directly. For example, you could add categories to NSArray and other Cocoa classes. As in the case of a subclass, you don’t need source code for the class you’re extending.
The methods added in a category can be used to extend the functionality of the class or override methods the class inherits. A category can also override methods declared in the class interface. However, it cannot reliably override methods declared in another category of the same class. A category is not a substitute for a subclass. It’s best if categories don’t attempt to redefine methods that are explicitly declared in the class’s @interface section. Also note that a class can’t define the same method more than once.
When a category overrides an inherited method, the new version can, as usual, incorporate the inherited version through a message to super. But there’s no way for a category method to incorporate a method with the same name defined for the same class.
You can also use categories to distribute the implementation of a new class into separate source files—for example, you could group the methods of a large class into several categories and put each category in a different file. When used like this, categories can benefit the development process in a number of ways:
They provide a simple way of grouping related methods. Similar methods defined in different classes can be kept together in the same source file.
They simplify the management of a large class when several developers contribute to the class definition.
They let you achieve some of the benefits of incremental compilation for a very large class.
They can help improve locality of reference for commonly used methods.
They enable you to configure a class differently for separate applications, without having to maintain different versions of the same source code.
Categories are also used to declare informal protocols (see “Informal Protocols ”), as discussed under “Declaring Interfaces for Others to Implement.”
Last updated: 2008-02-05