typestar

NSRange and C structs in Objective-C

Plain C structs flow between messages and locals.

#import <Foundation/Foundation.h>

int main(void) {
    @autoreleasepool {
        // Plain C structs flow between messages and locals.
        NSString *sticker = @"PROMO COPY - NOT FOR SALE";
        NSRange dash = [sticker rangeOfString:@" - "];

        if (dash.location != NSNotFound) {
            NSString *keep = [sticker substringToIndex:dash.location];
            NSLog(@"Sticker trimmed to: %@", keep);
        }
        // Structs build with designated initializers like any C.
        NSRange firstWord = { .location = 0, .length = 5 };
        NSLog(@"First word spans %lu chars from %lu",
              (unsigned long)firstWord.length,
              (unsigned long)firstWord.location);
    }
    return 0;
}

How it works

  1. rangeOfString: answers location and length in one struct.
  2. NSNotFound is the miss sentinel to test against.
  3. Designated initializers build structs C-style.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
596
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 C interop, step 23 of 27 in Language basics.

← Previous Next →