Best approach for downloading a list of 200-300 images/files from a folder

Discussion in 'iOS Programming' started by roeik, Mar 22, 2010.

  1. roeik macrumors member

    Joined:
    Dec 25, 2008
    #1
    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?
     
  2. Luke Redpath macrumors 6502a

    Joined:
    Nov 9, 2007
    Location:
    Colchester, UK
    #2
    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/
     
  3. roeik thread starter macrumors member

    Joined:
    Dec 25, 2008
    #3
    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?
     
  4. Luke Redpath macrumors 6502a

    Joined:
    Nov 9, 2007
    Location:
    Colchester, UK
    #4
    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.
     

Share This Page