I was reading this: does dispatch_async copy internal blocks
and I want to know how to get dispatch-async to nil out the block it copied onto the heap so that the block can be garbage collected.
Ok, so on the local stack, I create my block:
MyBlock aBlock = ^{
for (int i = 0; i < 10; i++) {
NSLog(@"holder is: %p, holder.block is %p", holder, holder.block);
sleep(1);
}
};
dispatch_queue_t queue = dispatch_queue_create(NULL, DISPATCH_QUEUE_SERIAL);
dispatch_async(queue, aBlock);
sleep(2); // give the queue some time to start executing the block
The block keeps executing simply because it is the block on the heap that is copied by dispatch_async. This is all expected behavior.
So my question is....is there a way to explicitly make this block on the heap be destroyed ?
Or will ARC memory manage that block for me from the heap when the dispatch_async has finished executing, and I personally can't do anything about it ?
Thank you!
For your updated question, you don't need to nil
anything. The block on the heap is just like any other reference counted object. Your scope has a strong reference to it for the duration of the scope of the variable aBlock
. And the asynchronous dispatch mechanism holds a strong reference to it until it has executed. When there are no strong references to it anymore, it is deallocated.