Initializers
Creating an object is a two-step process: alloc reserves zero-filled memory, and an initializer (a method whose name starts with init) gives the object a valid starting state. Writing good initializers is one of the first "real" skills in Objective-C.
Writing init
An initializer follows a fixed pattern:
#import <Foundation/Foundation.h>
@interface Timer : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic) NSInteger seconds;
@end
@implementation Timer
- (instancetype)init {
self = [super init]; // 1. let the superclass initialize first
if (self) { // 2. it may return nil on failure
_name = @"Untitled"; // 3. set up your own state (use ivars here)
_seconds = 60;
}
return self; // 4. return the initialized object
}
@end
int main(void) {
@autoreleasepool {
Timer *t = [[Timer alloc] init];
NSLog(@"%@: %ld s", t.name, (long)t.seconds);
}
return 0;
}Untitled: 60 s
Why each step matters:
[super init]runsNSObject's (or your superclass's) setup. Skipping it leaves the inherited part uninitialised.- An initializer may fail and return
nil; theif (self)check avoids touching memory in that case. - Inside
init, use the instance variables (_name) rather thanself.name, because a subclass might override the setter and expect a fully initialised object. - Always
return self.
Initializers with parameters
Most classes need some values to be valid, so they offer initWith… initializers. The return type instancetype means "an instance of the receiving class", so subclasses automatically get the right type.
#import <Foundation/Foundation.h>
@interface Product : NSObject
@property (nonatomic, copy, readonly) NSString *name;
@property (nonatomic, readonly) double price;
- (instancetype)initWithName:(NSString *)name price:(double)price;
+ (instancetype)productWithName:(NSString *)name price:(double)price;
@end
@implementation Product
- (instancetype)initWithName:(NSString *)name price:(double)price {
self = [super init];
if (self) {
_name = [name copy];
_price = price;
}
return self;
}
// A convenience factory method that wraps alloc + init
+ (instancetype)productWithName:(NSString *)name price:(double)price {
return [[self alloc] initWithName:name price:price];
}
- (NSString *)description {
return [NSString stringWithFormat:@"%@ ($%.2f)", self.name, self.price];
}
@end
int main(void) {
@autoreleasepool {
Product *lamp = [[Product alloc] initWithName:@"Desk lamp" price:34.9];
Product *cable = [Product productWithName:@"USB cable" price:7.5];
NSLog(@"%@", lamp);
NSLog(@"%@", cable);
}
return 0;
}Desk lamp ($34.90)
USB cable ($7.50)
Because the properties are readonly, an initializer is the only way to set them: the object is effectively immutable once created.
Designated and convenience initializers
When a class has several initializers, one of them is the designated initializer: the one that really sets everything up and calls super. All the others are convenience initializers that call the designated one on self with default values. Mark the designated one with NS_DESIGNATED_INITIALIZER so the compiler checks the rules.
#import <Foundation/Foundation.h>
@interface Alarm : NSObject
@property (nonatomic, readonly) NSInteger hour;
@property (nonatomic, readonly) NSInteger minute;
@property (nonatomic, copy, readonly) NSString *label;
- (instancetype)initWithHour:(NSInteger)hour minute:(NSInteger)minute
label:(NSString *)label NS_DESIGNATED_INITIALIZER;
- (instancetype)initWithHour:(NSInteger)hour minute:(NSInteger)minute;
- (instancetype)init;
@end
@implementation Alarm
// Designated: the only one that calls super
- (instancetype)initWithHour:(NSInteger)hour minute:(NSInteger)minute label:(NSString *)label {
self = [super init];
if (self) {
_hour = hour;
_minute = minute;
_label = [label copy];
}
return self;
}
// Convenience initializers delegate to self
- (instancetype)initWithHour:(NSInteger)hour minute:(NSInteger)minute {
return [self initWithHour:hour minute:minute label:@"Alarm"];
}
- (instancetype)init {
return [self initWithHour:7 minute:0];
}
- (NSString *)description {
return [NSString stringWithFormat:@"%02ld:%02ld %@", (long)self.hour, (long)self.minute, self.label];
}
@end
int main(void) {
@autoreleasepool {
NSLog(@"%@", [[Alarm alloc] initWithHour:6 minute:30 label:@"Gym"]);
NSLog(@"%@", [[Alarm alloc] initWithHour:22 minute:15]);
NSLog(@"%@", [Alarm new]);
}
return 0;
}06:30 Gym
22:15 Alarm
07:00 Alarm
The rules the compiler enforces:
| Rule | Why |
|---|---|
| A designated initializer calls a designated initializer of the superclass | so the inherited part is set up exactly once |
| A convenience initializer calls another initializer of self | so all paths end at the designated one |
| A subclass that adds a new designated initializer should override the superclass's designated ones | otherwise [[Sub alloc] init] would skip the subclass's setup |
Failable initializers
Returning nil from an initializer signals that the arguments were invalid. Callers must check the result:
#import <Foundation/Foundation.h>
@interface Percentage : NSObject
@property (nonatomic, readonly) double value;
- (instancetype)initWithValue:(double)value;
@end
@implementation Percentage
- (instancetype)initWithValue:(double)value {
if (value < 0 || value > 100) {
return nil; // invalid: no object
}
self = [super init];
if (self) {
_value = value;
}
return self;
}
@end
int main(void) {
@autoreleasepool {
double inputs[] = {42, 150, -3, 100};
for (int i = 0; i < 4; i++) {
Percentage *p = [[Percentage alloc] initWithValue:inputs[i]];
if (p) {
NSLog(@"%.0f%% accepted", p.value);
} else {
NSLog(@"%.0f rejected", inputs[i]);
}
}
}
return 0;
}42% accepted
150 rejected
-3 rejected
100% accepted
Tip: To forbid plain
initentirely (for a class that needs arguments), Apple headers write- (instancetype)init NS_UNAVAILABLE;. Then[[Percentage alloc] init]is a compile error.
Test yourself
What is the first thing an init method normally does?
- return self
- self = [super init]
- set the ivars
- call alloc
Which initializer should a convenience initializer call?
- [super init]
- Another initializer on self
- alloc
- dealloc
What does instancetype mean as a return type?
- Always NSObject *
- id with no type checking
- An instance of the class that received the message
- A class object