3

My project use ARC. I tested with the code below:

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

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

I think it output as:

string: (null)

but it actually output:

string: AAA

I don't understand it. What is the effect of __weak?

EDIT:

And this code below:

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

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

It also output as:

string: AAA
ThomasW
  • 16,981
  • 4
  • 79
  • 106
vietstone
  • 8,784
  • 16
  • 52
  • 79

1 Answers1

8
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);
Kazuki Sakamoto
  • 13,929
  • 2
  • 34
  • 96