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.
// In Account.m, before @implementation
@interface Account ()
@property (nonatomic, readwrite) double balance; // redeclare as writable
@property (nonatomic, strong) NSMutableArray *history;
- (void)logEvent:(NSString *)event;
@endUnlike 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.
#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:
#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:
#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?
- @interface Name (Private)
- @interface Name ()
- @extension Name
- @implementation Name ()
What can a class extension do that a category cannot?
- Add methods
- Add stored properties and instance variables
- Be used on NSString
- Override methods
A header declares @property (readonly) double balance;. How can the class itself use a setter?
- It can't
- Redeclare it readwrite in a class extension
- Use a category
- Make it atomic