A category allows you to add methods to an existing class—even to one to which you do not have the source. This is a powerful feature that allows you to extend the functionality of existing classes without subclassing. Using categories, you can also split the implementation of your own classes between several files. Class extensions are similar, but allow additional required API to be declared for a class in locations other than within the primary class @interface
block
Adding Methods to Classes
How you Use Categories
Categories of the Root Class
Extensions
You can add methods to a class by declaring them in an interface file under a category name and defining them in an implementation file under the same name. The category name indicates that the methods are additions to a class declared elsewhere, not a new class. You cannot, however, use a category to add additional instance variables to a class.
The methods the category adds become part of the class type. For example, methods added to the NSArray
class in a category are among the methods the compiler expects an NSArray
instance to have in its repertoire. Methods added to the NSArray
class in a subclass are not included in the NSArray
type. (This matters only for statically typed objects, since static typing is the only way the compiler can know an object’s class.)
Category methods can do anything that methods defined in the class proper can do. At runtime, there’s no difference. The methods the category adds to the class are inherited by all the class’s subclasses, just like other methods.
The declaration of a category interface looks very much like a class interface declaration—except the category name is listed within parentheses after the class name and the superclass isn’t mentioned. Unless its methods don’t access any instance variables of the class, the category must import the interface file for the class it extends:
#import "ClassName.h" |
@interface ClassName ( CategoryName ) |
// method declarations |
@end |
The implementation, as usual, imports its own interface. A common naming convention is that the base file name of the category is the name of the class the category extends followed by “+” followed by the name of the category. A category implementation (in a file named ClassName+CategoryName.m
) might therefore look like this:
#import "ClassName+CategoryName.h" |
@implementation ClassName ( CategoryName ) |
// method definitions |
@end |
Note that a category can’t declare additional instance variables for the class; it includes only methods. However, all instance variables within the scope of the class are also within the scope of the category. That includes all instance variables declared by the class, even ones declared @private
.
There’s no limit to the number of categories that you can add to a class, but each category name must be different, and each should declare and define a different set of methods.
There are several ways in which 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.
As 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.
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.
Simplify the management of a large class when several developers contribute to the class definition.
Let you achieve some of the benefits of incremental compilation for a very large class.
Can help improve locality of reference for commonly used methods.
Enable you to configure a class differently for separate applications, without having to maintain different versions of the same source code.
To declare informal protocols.
See “Informal Protocols ,” as discussed under “Declaring Interfaces for Others to Implement.”
Although the language currently allows you to use a category to override methods the class inherits, or even methods declared in the class interface, you are strongly discouraged from using this functionality. A category is not a substitute for a subclass. There are several significant shortcomings:
When a category overrides an inherited method, the method in the category can, as usual, invoke the inherited implementation via a message to super
. However, if a category overrides a method that already existed in the category's class, there is no way to invoke the original implementation.
A category cannot reliably override methods declared in another category of the same class.
This issue is of particular significance since many of the Cocoa classes are implemented using categories. A framework-defined method you try to override may itself have been implemented in a category, and so which implementation takes precedence is not defined.
The very presence of some methods may cause behavior changes across all frameworks. For example, if you add an implementation of windowWillClose:
to NSObject
, this will cause all window delegates to respond to that method and may modify the behavior of all instances of NSWindow
instances. This may cause mysterious changes in behavior and can lead to crashes.
A category can add methods to any class, including the root class. Methods added to NSObject
become available to all classes that are linked to your code. While this can be useful at times, it can also be quite dangerous. Although it may seem that the modifications the category makes are well understood and of limited impact, inheritance gives them a wide scope. You may be making unintended changes to unseen classes; you may not know all the consequences of what you’re doing. Moreover, others who are unaware of your changes won’t understand what they’re doing.
In addition, there are two other considerations to keep in mind when implementing methods for the root class:
Messages to super
are invalid (there is no superclass).
Class objects can perform instance methods defined in the root class.
Normally, class objects can perform only class methods. But instance methods defined in the root class are a special case. They define an interface to the runtime system that all objects inherit. Class objects are full-fledged objects and need to share the same interface.
This feature means that you need to take into account the possibility that an instance method you define in a category of the NSObject
class might be performed not only by instances but by class objects as well. For example, within the body of the method, self
might mean a class object as well as an instance. See the NSObject
class specification in the Foundation framework reference for more information on class access to root instance methods.
Class extensions are like “anonymous” categories, except that the methods they declare must be implemented in the main @implementation
block for the corresponding class.
It is common for a class to have a publicly declared API and to then have additional API declared privately for use solely by the class or the framework within which the class resides. You can declare such API in a category (or in more than one category) in a private header file or implementation file as described above. This works, but the compiler cannot verify that all declared methods are implemented.
For example, the compiler will compile without error the following declarations and implementation:
@interface MyObject : NSObject |
{ |
NSNumber *number; |
} |
- (NSNumber *)number; |
@end |
@interface MyObject (Setter) |
- (void)setNumber:(NSNumber *)newNumber; |
@end |
@implementation MyObject |
- (NSNumber *)number { |
return number; |
} |
@end |
Note that there is no implementation of the setNumber:
method. If it is invoked at runtime, this will generate an error.
Class extensions allow you to declare additional required API for a class in locations other than within the primary class @interface
block, as illustrated in the following example:
@interface MyObject : NSObject |
{ |
NSNumber *number; |
} |
- (NSNumber *)number; |
@end |
@interface MyObject () |
- (void)setNumber:(NSNumber *)newNumber; |
@end |
@implementation MyObject |
- (NSNumber *)number { |
return number; |
} |
- (void)setNumber:(NSNumber *)newNumber { |
number = newNumber; |
} |
@end |
Notice that in this case:
No name is given in the parentheses in the second @interface
block;
The implementation of the setNumber:
method appears within the main @implementation
block for the class.
The implementation of the setNumber:
method must appear within the main @implementation
block for the class (you cannot implement it in a category). If this is not the case, the compiler will emit a warning that it cannot find a method definition for setNumber:
.
© 2009 Apple Inc. All Rights Reserved. (Last updated: 2009-05-06)