Reputation: 737
I'm having a problem with __block variables in nested blocks. My question is, should a code like the following work?
__block NSString* s = nil;
[self methodWithBlock:^
{
s = [self methodThatReturnsAnAutoreleasedString];
[self methodWithBlock:^
{
[NSLog @"%d", s.length];
}];
}];
I assumed the inner block retained s
but that doesn't seem to be the case in my code. I get a "message sent to deallocated instance" when accessing s
in the inner block. If I retain s when I assign it (s = [[self methodThatReturnsAnAutoreleasedString] retain];
), it works fine.
Of course, that's not my actual code, which is more complex, but I just want to know if that minimal example should work fine. If so, I need to look for my problem elsewhere.
Upvotes: 0
Views: 635
Reputation: 539715
(I assume that you don't use ARC.) From the Transitioning to ARC Release Notes:
In manual reference counting mode,
__block id x;
has the effect of not retainingx
.
So your assumption is wrong, the block does not retain s
. You have to retain it if
methodWithBlock
works asynchronously.
Upvotes: 3