Understanding the behaviour of [NSData dataWithCon

2019-04-15 06:20发布

问题:

Following question/statement is limited to my understanding,let me know if i'm wrong here.

From : Issue with GCD and too many threads

Forward to jackslash's answer,i wonder most of the developers have a habbit of using [NSData dataWithContentsOfURL:URL] which certainly does seems to be blocking(until it's done).Which can be ideal if your fetching some small details through URL.But in case of multiple process(i mean while downloading multiple files),GCD has to create many many threads and is not a perfect way to download the data.

So some experts suggested to use GCDs abstraction called [NSURLConnection sendAsynchronousRequest:queue:completionHandler: to handle such situation(and is ideal also).

My only question is how does [NSURLConnection sendAsynchronousRequest:queue:completionHandler: will take the advantage over NSData dataWithContentsOfURL:URL] in terms of creating new threads and saving us from getting blocked?.

Really appreciate any of your documented answer.

回答1:

Your question isn't really about GCD: it's about the best strategy to download many files at the same time.

The best strategy simply is to not do it. Trying to download, say, 100 individual files at the same time is a bad idea, especially if the user is on a cellular connection (which they probably are). You're right to identify that dataWithContentsOfURL is also usually not a great idea.

That said, there's a middle ground here. It would be nice if there was a way to tell iOS "go download X number of files at a time, but no more than that". To do this we can use a NSOperationQueue. An operation queue contains a number of operations and places them into a queue (that in this case is running in the background). For example:

NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
[operationQueue setMaxConcurrentOperationCount:3];
[operationQueue addOperations:@[download1, download2, download3] waitUntilFinished:NO];

Here we've created an operation queue that can support three simultaneous downloads. The advantages of using an operation queue should be obvious. Many developers choose to use a library like AFNetworking to help them manage downloading, and there are lots of guides around to using both this and NSURLConnection in an operation queue.



回答2:

sendAsynchronousRequest:queue:completionHandler: doesn't use GCD for the actual downloading. The queue you pass in is only used to execute the completion block. The download itself will be using low level asynchronous socket APIs in its internal implementation so there won't be any blocking or unnecessary thread creation.