Categories
Inheritance is not the only way to add functionality to a class. With an Objective-C language construct called a category , you can add methods to an existing class, thereby extending its functionality—and the functionality of its subclasses.
A category interface declaration looks
like a class interface declaration, with one exception: the category
name is listed in parentheses after the class name, and the
superclass is not mentioned. For example, if you wanted to add a
rot13 method to the NSString
class to get the rot13 version of any string, the
category interface would be defined as shown in Example 1-11.
#import "NSString.h" @interface NSString (Obfuscation) - (NSString *)rot13; @end
The category’s implementation looks like the implementation of a class itself. Example 1-12 shows an interface implementation.
#import "Obfuscation.h"
@implementation NSString (Obfuscation)
- (NSString *)rot13 {
NSString * rot13string;
// Perform logic to shift each character by 13
return rot13string;
}
@endRemember that a category can’t declare new instance variables for a class; it can only add methods to an existing class.
Warning
A category is not a substitute for a subclass. You should not redefine methods already in a class or a class’s superclass—add only new methods to the class.
Protocols
Class and category interfaces define the methods that belong to a particular class. However, you might want many ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access