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
[[NSMutableArray alloc] init]is the canonical creation.- Class-method constructors like
arraywrap the same dance. - Classes are objects:
[crate class]answers with one.
Keywords and builtins used here
NSMutableArrayclassintlongmainreturnunsignedvoid
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.
Step 3 of 3 in Messages, step 6 of 27 in Language basics.