pub type dispatch_block_t = *mut DynBlock<dyn Fn()>;Expand description
The type of blocks submitted to dispatch queues, which take no arguments and have no return value.
When not building with Objective-C ARC, a block object allocated on or copied to the heap must be released with a -[release] message or the Block_release() function.
The declaration of a block literal allocates storage on the stack.
Therefore, this is an invalid construct:
dispatch_block_t block;
if (x) {
block = ^{ printf(“true\n”); };
} else {
block = ^{ printf(“false\n”); };
}
block(); // unsafe!!!
What is happening behind the scenes:
if (x) {
struct Block __tmp_1 = …; // setup details
block =
&
__tmp_1;
} else {
struct Block __tmp_2 = …; // setup details
block =
&
__tmp_2;
}
As the example demonstrates, the address of a stack variable is escaping the scope in which it is allocated. That is a classic C bug.
Instead, the block literal must be copied to the heap with the Block_copy() function or by sending it a -[copy] message.
See also Apple’s documentation