typestar

El inicializador designado en Objective-C

La danza del init: llama a super, prepara bajo el if, devuelve self.

#import <Foundation/Foundation.h>

@interface Crate : NSObject
@property (copy) NSString *genre;
- (instancetype)initWithGenre:(NSString *)genre;
@end

@implementation Crate
// The designated initializer: call super, set up, return self.
- (instancetype)initWithGenre:(NSString *)genre {
    self = [super init];
    if (self) {
        _genre = [genre copy];
    }
    return self;
}
@end

int main(void) {
    @autoreleasepool {
        Crate *crate = [[Crate alloc] initWithGenre:@"bebop"];
        NSLog(@"A crate of %@", crate.genre);
    }
    return 0;
}

Cómo funciona

  1. initWithGenre: devuelve instancetype — esta clase, sea cual sea.
  2. self = [super init] puede legalmente entregar otro objeto.
  3. _genre alcanza el ivar sintetizado directo dentro del init.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
25
Caracteres a escribir
509
Tokens
107
Ritmo de tres estrellas
60 tpm

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

Escribe este fragmento

Paso 3 de 3 en Clases; paso 9 de 27 en Fundamentos del lenguaje.

← Anterior Siguiente →