typestar

Dynamic typing in Objective-C

id holds anything; the questions get asked at run time.

#import <Foundation/Foundation.h>

int main(void) {
    @autoreleasepool {
        // id holds any object; the checks happen at run time.
        NSArray *mixedBin = @[ @"Low", @1977, @"Heroes" ];
        for (id item in mixedBin) {
            if ([item isKindOfClass:[NSString class]]) {
                NSLog(@"Title: %@", item);
            } else if ([item isKindOfClass:[NSNumber class]]) {
                NSLog(@"Year: %@", item);
            }
        }
        // respondsToSelector: asks before sending.
        id thing = @"quiet storm";
        NSLog(@"Can shout? %d",
              [thing respondsToSelector:@selector(uppercaseString)]);
    }
    return 0;
}

How it works

  1. id is the any-object type; collections mix freely.
  2. isKindOfClass: sorts a mixed bin at run time.
  3. respondsToSelector: asks before sending — @selector names one.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
523
Tokens
115
Three-star pace
60 tpm

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

Type this snippet

Step 3 of 3 in Protocols & dynamism, step 21 of 27 in Language basics.

← Previous Next →