typestar

alloc and init in Objective-C

Two-step birth: the class allocates, the instance initializes.

#import <Foundation/Foundation.h>

int main(void) {
    @autoreleasepool {
        // Two-step birth: the class allocates, the instance initializes.
        NSMutableArray *crate = [[NSMutableArray alloc] init];
        [crate addObject:@"Kind of Blue"];
        NSLog(@"Crate holds %lu", (unsigned long)[crate count]);

        // Class-method constructors wrap the same dance.
        NSMutableArray *wall = [NSMutableArray array];
        [wall addObject:@"A Love Supreme"];

        // Classes are objects too; ask one its name.
        NSLog(@"Built by %@", [crate class]);
    }
    return 0;
}

How it works

  1. [[NSMutableArray alloc] init] is the canonical creation.
  2. Class-method constructors like array wrap the same dance.
  3. Classes are objects: [crate class] answers with one.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
516
Tokens
87
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 80 seconds.

Type this snippet

Step 3 of 3 in Messages, step 6 of 27 in Language basics.

← Previous Next →