typestar

Block enumeration in Objective-C

The collection drives; your block rides along with index and stop.

#import <Foundation/Foundation.h>

int main(void) {
    @autoreleasepool {
        NSArray<NSString *> *arrivals =
            @[ @"Ege Bamyasi", @"Marquee Moon", @"Remain in Light" ];

        // The block receives the object, its index, and a stop switch.
        [arrivals enumerateObjectsUsingBlock:
            ^(NSString *title, NSUInteger idx, BOOL *stop) {
                NSLog(@"Bin %lu: %@", (unsigned long)idx, title);
                if ([title isEqualToString:@"Marquee Moon"]) {
                    *stop = YES;
                }
            }];
    }
    return 0;
}

How it works

  1. enumerateObjectsUsingBlock: passes object, index, and a stop flag.
  2. *stop = YES ends the walk early from inside the block.
  3. The block parameter types are spelled right in the call.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
442
Tokens
94
Three-star pace
60 tpm

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

Type this snippet

Step 2 of 3 in Enumeration, step 14 of 27 in Language basics.

← Previous Next →