TExcelTAD
Home › Objective-C › Class Extensions

Class Extensions

A class extension looks like a category without a name, @interface ClassName (), and it serves a different purpose: declaring the private part of your own class. It is written in the .m file, so other files never see it.

objc
// In Account.m, before @implementation
@interface Account ()
@property (nonatomic, readwrite) double balance;   // redeclare as writable
@property (nonatomic, strong) NSMutableArray *history;
- (void)logEvent:(NSString *)event;
@end

Unlike a category, an extension can add properties with synthesized storage and instance variables, because the compiler sees it together with the class's @implementation.

Public readonly, private readwrite

The most common use: the public header promises a readonly property, and the extension makes it writable inside the class. Outside code can read but not change it.

objc · try it yourself
#import <Foundation/Foundation.h>

// ---- Account.h (public) ----
@interface Account : NSObject
@property (nonatomic, copy, readonly) NSString *owner;
@property (nonatomic, readonly) double balance;
- (instancetype)initWithOwner:(NSString *)owner;
- (BOOL)withdraw:(double)amount;
- (void)deposit:(double)amount;
- (NSArray *)statement;
@end

// ---- Account.m (private) ----
@interface Account ()
@property (nonatomic, readwrite) double balance;
@property (nonatomic, strong) NSMutableArray *history;
@end

@implementation Account
- (instancetype)initWithOwner:(NSString *)owner {
    self = [super init];
    if (self) {
        _owner = [owner copy];
        _history = [NSMutableArray array];
    }
    return self;
}
- (void)deposit:(double)amount {
    self.balance += amount;                          // private setter
    [self.history addObject:[NSString stringWithFormat:@"+%.2f", amount]];
}
- (BOOL)withdraw:(double)amount {
    if (amount > self.balance) {
        [self.history addObject:[NSString stringWithFormat:@"declined %.2f", amount]];
        return NO;
    }
    self.balance -= amount;
    [self.history addObject:[NSString stringWithFormat:@"-%.2f", amount]];
    return YES;
}
- (NSArray *)statement {
    return [self.history copy];
}
@end

int main(void) {
    @autoreleasepool {
        Account *acc = [[Account alloc] initWithOwner:@"Ines"];
        [acc deposit:100];
        [acc withdraw:30];
        BOOL ok = [acc withdraw:500];
        NSLog(@"%@ has %.2f (big withdrawal ok? %d)", acc.owner, acc.balance, ok);
        NSLog(@"statement: %@", [acc.statement componentsJoinedByString:@", "]);
        // acc.balance = 1e6;   // error: the public property is readonly
    }
    return 0;
}
Ines has 70.00 (big withdrawal ok? 0)
statement: +100.00, -30.00, declined 500.00

Private methods and conformance

An extension can also declare private methods (handy for documenting helpers) and adopt protocols privately, so the rest of the app doesn't know the class is, say, a delegate of something:

objc · try it yourself
#import <Foundation/Foundation.h>

@protocol TickListener <NSObject>
- (void)tick:(NSInteger)n;
@end

@interface Clock : NSObject
@property (nonatomic, weak) id<TickListener> listener;
- (void)runTicks:(NSInteger)count;
@end
@implementation Clock
- (void)runTicks:(NSInteger)count {
    for (NSInteger i = 1; i <= count; i++) [self.listener tick:i];
}
@end

// ---- public interface: no mention of TickListener ----
@interface Stopwatch : NSObject
- (NSString *)measure:(NSInteger)ticks;
@end

// ---- private extension ----
@interface Stopwatch () <TickListener>
@property (nonatomic) NSInteger elapsed;
- (NSString *)formatTime;
@end

@implementation Stopwatch
- (NSString *)measure:(NSInteger)ticks {
    Clock *clock = [Clock new];
    clock.listener = self;
    self.elapsed = 0;
    [clock runTicks:ticks];
    return [self formatTime];
}
- (void)tick:(NSInteger)n {
    self.elapsed = n;
}
- (NSString *)formatTime {
    return [NSString stringWithFormat:@"%02ld:%02ld", (long)(self.elapsed / 60), (long)(self.elapsed % 60)];
}
@end

int main(void) {
    @autoreleasepool {
        Stopwatch *sw = [Stopwatch new];
        NSLog(@"%@", [sw measure:75]);
        NSLog(@"%@", [sw measure:9]);
    }
    return 0;
}
01:15
00:09

Instance variables in the implementation

For simple private state you can also skip properties and declare ivars in braces after @implementation. You saw this in the Classes lesson; it's equivalent to declaring them in an extension:

objc · try it yourself
#import <Foundation/Foundation.h>

@interface RateLimiter : NSObject
- (instancetype)initWithLimit:(NSInteger)limit;
- (BOOL)allowRequest;
@end

@implementation RateLimiter {
    NSInteger _limit;
    NSInteger _used;
}
- (instancetype)initWithLimit:(NSInteger)limit {
    self = [super init];
    if (self) { _limit = limit; }
    return self;
}
- (BOOL)allowRequest {
    if (_used >= _limit) return NO;
    _used++;
    return YES;
}
@end

int main(void) {
    @autoreleasepool {
        RateLimiter *limiter = [[RateLimiter alloc] initWithLimit:3];
        for (int i = 1; i <= 5; i++) {
            NSLog(@"request %d: %@", i, [limiter allowRequest] ? @"allowed" : @"throttled");
        }
    }
    return 0;
}
request 1: allowed
request 2: allowed
request 3: allowed
request 4: throttled
request 5: throttled

Category vs. extension

Category (Name) Extension ()
Where any file, any class (even Apple's) the class's own .m file
Adds methods yes yes (declarations; implemented in the main @implementation)
Adds stored properties / ivars no yes
Typical purpose extend other classes, split large classes hide private state and methods

Note: "Private" in Objective-C means not visible to the compiler elsewhere. The runtime still knows about every method and property, which is what makes tools like KVC and introspection work.

Test yourself

How is a class extension written?

  1. @interface Name (Private)
  2. @interface Name ()
  3. @extension Name
  4. @implementation Name ()

What can a class extension do that a category cannot?

  1. Add methods
  2. Add stored properties and instance variables
  3. Be used on NSString
  4. Override methods

A header declares @property (readonly) double balance;. How can the class itself use a setter?

  1. It can't
  2. Redeclare it readwrite in a class extension
  3. Use a category
  4. Make it atomic