typestar

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

  1. @interface NSString (Shelf) opens the category.
  2. The implementation block pairs with the same name.
  3. Every NSString instance now answers shelfLabel.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Protocols & dynamism, step 20 of 27 in Language basics.

← Previous Next →