typestar

NSDictionary in Objective-C

@{} pairs keys with values; a miss answers nil.

#import <Foundation/Foundation.h>

int main(void) {
    @autoreleasepool {
        // @{} pairs keys with values; subscripts read and miss to nil.
        NSDictionary<NSString *, NSNumber *> *stock = @{
            @"Kind of Blue" : @7,
            @"Maggot Brain" : @2,
        };
        NSLog(@"Titles stocked: %lu", (unsigned long)[stock count]);
        NSLog(@"Maggot Brain: %@ copies", stock[@"Maggot Brain"]);
        NSLog(@"Missing title: %@", stock[@"Pet Sounds"]);

        for (NSString *title in [stock allKeys]) {
            NSLog(@"- %@", title);
        }
    }
    return 0;
}

How it works

  1. @{ key : value } is the literal; subscripting reads it.
  2. A missing key returns nil, printed as (null).
  3. allKeys hands the keys to a for-in loop.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
484
Tokens
110
Three-star pace
60 tpm

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

Type this snippet

Step 2 of 3 in Collections, step 11 of 27 in Language basics.

← Previous Next →