Last Updated: February 25, 2016
·
1.621K
· mattmassicotte

Be careful with __block and autoreleased objects

I ran into an issue today that made me realize you have to be really careful when using the __block storage qualifier. Consider the following code:

__block NSString* string;
dispatch_sync(dispatch_get_main_queue(), ^{
    string = [NSString stringWithString:@"I'm autoreleased!"];
});

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

The main queue will cycle its autorelease pool before this dispatch_sync returns, leaving a dangling pointer in the string value. That NSLog line will definitely not do what you want, and could crash.

This is just an easy way to demonstrate this problem. You could imagine any code taking a block might have an autorelease pool in place.

I suspect that ARC handles this case better, but I've not tried. Definitely something to watch out for.

Update: Confirmed. Under ARC, __block implies strong, so you are safe in that case.