dispatch_queue_t callerQueue = dispatch_get_current_queue();
dispatch_retain(callerQueue);
dispatch_queue_t downloadQueue = dispatch_queue_create("Download Queue",NULL);
dispatch_async(downloadQueue,
^{
//some code that accesses a web service
dispatch_async(callerQueue,
^{
//some code that accesses UI
});
});
dispatch_release(downloadQueue);
NSLog(@"great successing!");
The problem is that "Great successing!" never shows up, and nothing ever happens beyond the end of the code outermost dispatch_async
block. I'm not sure what I'm doing wrong but I know there is something seriously wrong with this.
You are releasing your download queue too early. You need to wait until after it has executed the block. The dispatch_async
man page suggests putting the release at the end of the block.
It is important to remember to retain the destination queue before the first call to
dispatch_async()
, and to release that queue at the end of the completion callback to ensure the destination queue is not deallocated while the completion callback is pending.
There are a couple of problems with this code:
You don't need to retain the callerQueue after creating it. It's already created with retain count of 1 and will presumably go away once you release it later. By retaining it twice, you are potentially creating a leak.
You should never do UI operations on any queue other than the main queue (not the callerQueue in this case).
The rest of the code looks fine (and you don't have to release the download queue from within the block, as others are suggesting, since the dispatch_async() call will also retain it. There must be more to this code fragment we're missing (like, does the code exit right after doing the NSLog()?).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With