The designated initializer in Objective-C
The init dance: call super, set up under the if, return self.
#import <Foundation/Foundation.h>
@interface Crate : NSObject
@property (copy) NSString *genre;
- (instancetype)initWithGenre:(NSString *)genre;
@end
@implementation Crate
// The designated initializer: call super, set up, return self.
- (instancetype)initWithGenre:(NSString *)genre {
self = [super init];
if (self) {
_genre = [genre copy];
}
return self;
}
@end
int main(void) {
@autoreleasepool {
Crate *crate = [[Crate alloc] initWithGenre:@"bebop"];
NSLog(@"A crate of %@", crate.genre);
}
return 0;
}
How it works
initWithGenre:returnsinstancetype— this class, whichever it is.self = [super init]may legally hand back a different object._genrereaches the synthesized ivar directly inside init.
Keywords and builtins used here
CrateNSObjectNSStringcopyifinstancetypeintreturnselfsupervoid
The run, in numbers
- Lines
- 25
- Characters to type
- 509
- Tokens
- 107
- Three-star pace
- 60 tpm
At the three-star pace of 60 tokens a minute, this run takes about 107 seconds.
Step 3 of 3 in Classes, step 9 of 27 in Language basics.