typestar

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

  1. initWithGenre: returns instancetype — this class, whichever it is.
  2. self = [super init] may legally hand back a different object.
  3. _genre reaches the synthesized ivar directly inside init.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in Classes, step 9 of 27 in Language basics.

← Previous Next →