Categories
A category adds methods to an existing class, even one you don't have the source for, such as NSString or NSArray. Every instance of the class (and its subclasses) gets the new methods immediately. Swift calls the same idea an extension.
Adding methods to NSString
#import <Foundation/Foundation.h>
// NSString+Text.h
@interface NSString (Text)
- (NSString *)reversedString;
- (BOOL)isPalindrome;
- (NSUInteger)wordCount;
@end
// NSString+Text.m
@implementation NSString (Text)
- (NSString *)reversedString {
NSMutableString *result = [NSMutableString stringWithCapacity:self.length];
for (NSInteger i = (NSInteger)self.length - 1; i >= 0; i--) {
[result appendFormat:@"%C", [self characterAtIndex:i]];
}
return result;
}
- (BOOL)isPalindrome {
NSString *letters = [[self lowercaseString] stringByReplacingOccurrencesOfString:@" " withString:@""];
return [letters isEqualToString:[letters reversedString]];
}
- (NSUInteger)wordCount {
NSUInteger count = 0;
for (NSString *part in [self componentsSeparatedByString:@" "]) {
if (part.length > 0) count++;
}
return count;
}
@end
int main(void) {
@autoreleasepool {
NSLog(@"%@", [@"stressed" reversedString]);
NSLog(@"'Never odd or even' palindrome? %d", [@"Never odd or even" isPalindrome]);
NSLog(@"'Objective-C' palindrome? %d", [@"Objective-C" isPalindrome]);
NSLog(@"%lu words", (unsigned long)[@" categories add methods " wordCount]);
}
return 0;
}desserts
'Never odd or even' palindrome? 1
'Objective-C' palindrome? 0
3 words
The name in parentheses (Text) is the category's name. By convention the files are called ClassName+CategoryName.h/.m, and other files #import "NSString+Text.h" to use the methods.
Categories on collections
#import <Foundation/Foundation.h>
@interface NSArray (Functional)
- (NSArray *)mappedWith:(id (^)(id obj))transform;
- (NSArray *)filteredWith:(BOOL (^)(id obj))test;
- (id)reducedFrom:(id)initial with:(id (^)(id acc, id obj))combine;
@end
@implementation NSArray (Functional)
- (NSArray *)mappedWith:(id (^)(id))transform {
NSMutableArray *out = [NSMutableArray arrayWithCapacity:self.count];
for (id obj in self) {
[out addObject:transform(obj)];
}
return [out copy];
}
- (NSArray *)filteredWith:(BOOL (^)(id))test {
NSMutableArray *out = [NSMutableArray array];
for (id obj in self) {
if (test(obj)) [out addObject:obj];
}
return [out copy];
}
- (id)reducedFrom:(id)initial with:(id (^)(id, id))combine {
id acc = initial;
for (id obj in self) {
acc = combine(acc, obj);
}
return acc;
}
@end
int main(void) {
@autoreleasepool {
NSArray *nums = @[@1, @2, @3, @4, @5, @6];
NSArray *squares = [nums mappedWith:^id(NSNumber *n) { return @(n.integerValue * n.integerValue); }];
NSArray *even = [squares filteredWith:^BOOL(NSNumber *n) { return n.integerValue % 2 == 0; }];
NSNumber *sum = [even reducedFrom:@0 with:^id(NSNumber *acc, NSNumber *n) {
return @(acc.integerValue + n.integerValue);
}];
NSLog(@"squares: %@", [squares componentsJoinedByString:@" "]);
NSLog(@"even squares: %@", [even componentsJoinedByString:@" "]);
NSLog(@"sum: %@", sum);
}
return 0;
}squares: 1 4 9 16 25 36
even squares: 4 16 36
sum: 56
Organizing your own classes
Categories also split a big class into themed files, for example a model class with a separate (Formatting) category:
#import <Foundation/Foundation.h>
@interface Invoice : NSObject
@property (nonatomic) NSInteger cents;
@property (nonatomic, copy) NSString *customer;
@end
@implementation Invoice
@end
@interface Invoice (Formatting)
- (NSString *)formattedAmount;
- (NSString *)line;
@end
@implementation Invoice (Formatting)
- (NSString *)formattedAmount {
return [NSString stringWithFormat:@"$%ld.%02ld", (long)(self.cents / 100), (long)(self.cents % 100)];
}
- (NSString *)line {
return [NSString stringWithFormat:@"%-10@ %10@", self.customer, [self formattedAmount]];
}
@end
int main(void) {
@autoreleasepool {
Invoice *a = [Invoice new];
a.customer = @"Acme";
a.cents = 125050;
Invoice *b = [Invoice new];
b.customer = @"Globex";
b.cents = 999;
NSLog(@"%@", [a line]);
NSLog(@"%@", [b line]);
}
return 0;
}Acme $1250.50
Globex $9.99
Rules and pitfalls
| Can a category… | |
|---|---|
| add instance and class methods | yes |
declare @property |
yes, but it can't synthesize storage: you must write the accessors (often with associated objects) |
| add instance variables | no |
| access the class's private ivars | only if visible in the headers it imports |
| override an existing method | technically yes, but don't: which version wins is undefined if two categories do it |
Warning: Always prefix category methods on system classes, e.g.
tad_reversedString. If Apple later adds areversedStringmethod toNSString, or another library adds one, the two collide silently and one replaces the other at run time. The examples here skip the prefix for readability.
Test yourself
What can a category add to an existing class?
- Instance variables
- Methods
- A new superclass
- Synthesized property storage
What is the conventional file name for a category Text on NSString?
- NSStringText.h
- NSString+Text.h
- Text(NSString).h
- NSString-Text.m
Why prefix category methods on system classes?
- Objective-C requires it
- To avoid clashing with methods Apple or other libraries add later
- For performance
- So they can be overridden