Categories in Objective-C
Add methods to a class you do not own — even NSString.
#import <Foundation/Foundation.h>
// A category adds methods to a class you do not own -- even NSString.
@interface NSString (Shelf)
- (NSString *)shelfLabel;
@end
@implementation NSString (Shelf)
- (NSString *)shelfLabel {
return [[self uppercaseString] stringByAppendingString:@" //"];
}
@end
int main(void) {
@autoreleasepool {
NSLog(@"%@", [@"ambient" shelfLabel]);
NSLog(@"%@", [@"krautrock" shelfLabel]);
}
return 0;
}
How it works
@interface NSString (Shelf)opens the category.- The implementation block pairs with the same name.
- Every NSString instance now answers
shelfLabel.
Keywords and builtins used here
NSStringintreturnselfshelfLabelvoid
The run, in numbers
- Lines
- 20
- Characters to type
- 427
- Tokens
- 82
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 76 seconds.
Step 2 of 3 in Protocols & dynamism, step 20 of 27 in Language basics.