Note that there are some explanatory texts on larger screens.

plurals
  1. PONSURLConnection vs. NSData + GCD
    primarykey
    data
    text
    <p><code>NSData</code> has always had a very convenient method called <code>+dataWithContentsOfURL:options:error:</code>. While convenient, it also blocks execution of the current thread, which meant it was basically useless for production code (Ignoring <code>NSOperation</code>). I used this method so infrequently, I completely forgot that it existed. Until recently.</p> <p>The way I've been grabbing data from the tubes is the standard <code>NSURLConnectionDelegate</code> approach: Write a download class that handles the various <code>NSURLConnectionDelegate</code> methods, gradually build up some data, handle errors, etc. I'll usually make this generic enough to be reused for as many requests as possible.</p> <p>Say my typical downloader class runs somewhere in the ballpark of 100 lines. That's 100 lines to do asynchronously what <code>NSData</code> can do synchronously in one line. For more complexity, that downloader class needs a delegate protocol of its own to communicate completion and errors to its owner, and the owner needs to implement that protocol in some fashion.</p> <p>Now, enter Grand Central Dispatch, and I can do something as fantastically simple as:</p> <pre><code>dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) { NSData* data = [NSData dataWithContentsOfURL:someURL]; // Process data, also async... dispatch_async(dispatch_get_main_queue(), ^(void) { // Back to the main thread for UI updates, etc. }); }); </code></pre> <p>And I can throw that sucker in anywhere I want, right in-line. No need for a download class, no need to handle connection delegate methods: Easy async data in just a few lines. The disparity between this approach and my pre-GCD approach is of a magnitude great enough to trigger the Too Good to be True Alarm.</p> <p>Thus, my question: Are there any caveats to using <code>NSData</code> + GCD for simple data download tasks instead of <code>NSURLConnection</code> (Assuming I don't care about things like download progress)?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload