Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

roeik

macrumors member
Original poster
Dec 25, 2008
80
0
Hello All,

I am considering what would be the best approach of downloading 200-300 images from a folder on a server. I have a csv file with the urls of the files, so it just a question of speed.

I was thinking of using NSData dataWithContentsOfURL and NSThread.

Will that work? If so, how many threads (each to download a file) Can I run simultaneously?
 
I was thinking of using NSData dataWithContentsOfURL and NSThread.

Will that work?

Yes, but its not the best way of doing it.

My advice would be to create a subclass of NSOperation to handle this and stick it on an NSOperationQueue. You should rarely have to deal directly with NSThread when there are better alternatives (NSOperation, or asynchronous APIs).

I've seen conflicting advice on this, but Apple recommends that even when using an asynchronous API, like NSURLConnection, that you run it in a background thread so the asynchronous methods do not get tied up whilst the main run loop handles UI updates.

Writing NSOperation's are relatively simple (read the documentation), but if you are going to use asynchronous APIs in an operation, your operation needs to be concurrent, so you'll probably want to read this article:
http://www.dribin.org/dave/blog/archives/2009/05/05/concurrent_operations/
 
Thanks for your reply.

I read the article and it was very useful. It seems that NSOperation class will be less pain then using NSThread, which is great.

However, there were a few conceptual things I didn't understand from the article. How come NSOperationQueue is non-concurrent, if it is running a number of operations in parallel. Wouldn't this be concurrent?

Also, I never used (so far) the NSData datawithcontentofurl method, but it seems way simpler to use this then using NSURLConnection when subclassing NSOperation. The article says:

"The only caveat is that the lifetime of an operation is the main method. Once that method returns, the operation is finished and it gets removed from the queue. If you want to use a class that has an asynchronous API, you have to jump through some hoops. Typically you have to play games with the run loop to ensure that the main method doesn’t return prematurely."

Instead of NSURLConnection, would I be able to subclass of NSOperation but use NSData datawithcontentofurl thus solving the problem?
 
You can use a synchronous method in an NSOperation, yes, and it would be simpler although possibly not as performant as using an optimized asynchronous API.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.