Pregunta

Mi proyecto usa arco. Probé con el siguiente código:

NSString __weak *string;
@autoreleasepool {
        string = [NSString stringWithString:@"AAA"];
}

NSLog(@"string: %@", string);

Creo que sale como:

string: (null)

Pero en realidad sale:

string: AAA

No lo entiendo. ¿Cuál es el efecto de __weak?

EDITAR:

Y este código a continuación:

NSString __weak *string;
NSString __strong *str;
@autoreleasepool {
    str = [NSString stringWithFormat:@"%@", @"AAA" ];
    string = str;
}

NSLog(@"string: %@", string);

También sale como:

string: AAA
¿Fue útil?

Solución

NSString __weak *string;
@autoreleasepool {
        string = [NSString stringWithFormat:@"%@", @"AAA"];
}

NSLog(@"string: %@", string);

it outputs as the following what you want.

string: (null)

Thus,

string = [NSString stringWithString:@"AAA"];

is same as

string = @"AAA";

the constant string literal that is not allocated in the heap.

EDITED:

str variable has still strong reference for the autoreleased object.

The following code is what exactly you want.

NSString __weak *string;
{
    NSString __strong *str;
    @autoreleasepool {
        str = [NSString stringWithFormat:@"%@", @"AAA" ];
        string = str;
    }
}
NSLog(@"string: %@", string);

And

NSString __weak *string;
@autoreleasepool {
    NSString __strong *str;
    str = [NSString stringWithFormat:@"%@", @"AAA" ];
    string = str;
}
NSLog(@"string: %@", string);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top