Can someone explain the relationship between asynchronous NSURL requests and GCD and NSOperationQueues?
I am not sure when to use each.
Right now, I have been “getting away” with asynchronous NSURL requests when I need to fetch/upload data to the server. But it has been suggested that I should use GCD. My problem is I do not know in what real life examples GCD would be better. Does anyone have any common use cases for me? And if I use GCD to store a queue of 10 asynchronous NSURL GET requests, for example, how would this benefit me? Does it even make sense to have an asynchronous NSURL request inside grand central dispatch queue or an NSOperationQueue?
Thank you!
What is particularly confusing in your case is that we’re mixing an HTTP request queue (where requests would be sent one after the other) and an operation queue (where random computational work is executed one task after the other).
A standard
NSURLConnectioninstance calls its delegate on the main thread, which is OK if you’re not doing complex work on the data or on your UI at that time. But say you need to download a big file and write it chunk by chunk as a file on disk, all while scrolling down a table view. Now your scrolling might get choppy when you write data on the disk, blocking the main thread.That’s where
GCDor its higher level abstractionNSOperationQueuecomes into play. To solve this issue, you need to offload your data write calls off of the main thread. You can do that by specifying anNSOperationQueueinstance on yourNSURLConnectionviasetDelegateQueue:. This will ensure your delegate, and therefore your write calls, will be called in a background thread. You can also leave the delegate calls on the main thread, and wrap your expensive write calls inside a block which you will then execute off the main thread withdispatch_async. NowNSOperationQueuebasically wraps a dispatch queue, and you’re avoiding an extra thread switch by using it over a raw dispatch queue so I would recommend theNSOperationQueuesolution (which also happens to looks simpler).AFNetworkingis a great library, and it solves this issue in a third way: it fires off anNSThreadwhich is dedicated toNSURLConnectiondelegate calls. That’s the pre-GCD way of offloading work off the main thread. Although it works, GCD offers a more efficient and good-citizen way of presenting your background work to the system.Last, if you’re looking for an HTTP request queue, Cocoa doesn’t provide it. You will have to either build a scheduler yourself, or as you already figured it out use
AFNetworkingwhich again is a great choice.If you’re interested in this topic, GCD has a lot more to offer than just hosting
NSURLConnectiondelegate calls, and I would recommend you read Apple’s great Concurrency Programming Guide or watch the excellent WWDC 2011 videos on GCD (Blocks and Grand Central Dispatch in Practice and Mastering Grand Central Dispatch).