typestar

NSRange y structs de C en Objective-C

Los structs planos de C fluyen entre mensajes y locales.

#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;
}

Cómo funciona

  1. rangeOfString: responde ubicación y largo en un struct.
  2. NSNotFound es el centinela de fallo contra el que probar.
  3. Los inicializadores designados arman structs al estilo C.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
20
Caracteres a escribir
596
Tokens
110
Ritmo de tres estrellas
60 tpm

Al ritmo de tres estrellas de 60 tokens por minuto, este intento toma unos 110 segundos.

Escribe este fragmento

Paso 2 de 3 en Interop con C; paso 23 de 27 en Fundamentos del lenguaje.

← Anterior Siguiente →