Retired Document
Important: This document may not represent best practices for current development. Links to downloads and other resources may no longer be valid.
Category
You use categories to define additional methods of an existing class—even one whose source code is unavailable to you—without subclassing. You typically use a category to add methods to an existing class, such as one defined in the Cocoa frameworks. The added methods are inherited by subclasses and are indistinguishable at runtime from the original methods of the class. You can also use categories of your own classes to:
Distribute the implementation of your own classes 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.
Declare private methods.
You 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 an extension to a class declared elsewhere, not a new class.
Declaration
The declaration of a category interface looks very much like a class interface declaration—except that the category name is listed within parentheses after the class name and the superclass isn’t mentioned. A category must import the interface file for the class it extends:
#import "SystemClass.h" |
@interface SystemClass (CategoryName) |
// method declarations |
@end |
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. This category might be declared in a file named SystemClass+CategoryName.h
.
If you use a category to declare private methods of one of your own classes, you can put the declaration in the implementation file before the @implementation
block:
#import "MyClass.h" |
@interface MyClass (PrivateMethods) |
// method declarations |
@end |
@implementation MyClass |
// method definitions |
@end |
Implementation
If you use a category to declare private methods of one of your own classes, you can put the implementation in your class’s @implementation
block. If you use a category to extend a class to which you don’t have source code, or to distribute the implementation of your own class, you put the implementation in a file named <ClassName>+CategoryName.m
The implementation, as usual, imports its own interface. A category implementation might therefore look like this:
#import "SystemClass+CategoryName.h" |
@implementation SystemClass ( CategoryName ) |
// method definitions |
@end |
Copyright © 2018 Apple Inc. All Rights Reserved. Terms of Use | Privacy Policy | Updated: 2018-04-06