Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when a block is set to nil during its execution?

Suppose I have an object with a strong reference to a block. Sometime during the execution of that block, the strong reference is set to nil. Is the block guaranteed to finish its execution, or can this cause a crash? I've seen exc-bad-access errors, but I can't produce them reliably, so I don't know exactly why they pop up.

For example:

-(void)method
{
    self.block = ^{
        //code
        self.block = nil;
        //more code - crash here?
    }
}

-(void)otherMethod
{
    block();
}
like image 801
Aaron Avatar asked Sep 04 '12 23:09

Aaron


1 Answers

The documents don't seem to guarantee that a block will be retained while it is executing. Conversely, the documentation for GCD calls such as dispatch_async does make such guarantees. From that it would seem you can't assume that an ordinary call into a block will retain it.

So in your code you probably want:

-(void)otherMethod
{
    dispatch_block_t localBlock = Block_copy(block);
    localBlock();
    Block_release(localBlock);
}
like image 161
Tommy Avatar answered Sep 21 '22 16:09

Tommy