views:

188

answers:

2

First, I'm using an NSURLConnection to download JSON data from twitter. Then, I'm using a second NSURLConnection to download corresponding user avatar images (the urls to the images are parsed from the first data download).

For the first data connection, I have my TwitterViewController set as the NSURLConnection delegate. I've created a separate class (ImageDownloadDelegate) to function as the delegate for a second NSURLConnection that handles the images. After the tweets are finished downloading, I'm using this code to get the avatars:

for(int j=0; j<[self.tweets count]; j++){
    ImageDownloadDelegate *imgDelegate = [[ImageDownloadDelegate alloc] init];

    Tweet *myTweet = [self.tweets objectAtIndex:j];
    imgDelegate.tweet = myTweet;
    imgDelegate.table = timeline; //to reload the data

    NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:myTweet.imageURL]
                                                                  cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                              timeoutInterval:60];
    imgConnection = [[NSURLConnection alloc] initWithRequest:request delegate:imgDelegate];
    [imgDelegate release];  
}

So basically a new instance of the delegate class is created for each image that needs to be downloaded. Is this the best way to go about this? If I were to create only one instance of the delegate class there's no way to figure out which image is associated with which tweet, correct? Nor would I be able to figure out the exact order in which the images are being downloaded.

The algorithm works fine... I'm just wondering if I'm going about it the most efficient way .

A: 

You might perhaps use the queuing feature of ASIHTTPRequest instead. You can create an ASINetworkQueue to handle a ordered queue of requests, and each request can perform behaviors on completion, so that you can track requests with responses.

Requests are based on the NSOperation class, and the queue on NSOperationQueue, so this framework does a lot of the coding work for you.

Alex Reynolds
+2  A: 

Put image downloads into something like an NSOperationQueue.

When the image download is done, save it to the caches directory, then send out a notification containing the original image URL, and the filename the image is now located at.

Anything that wants the image can listen for the notification. If nothing cares anymore (say cells that have scrolled off the screen) then they will have unsubscribed from notifications, so the image will just sit there until the system cleans out your cache directory...

It's also trivial with this system to check and see if an image already exists on disk before you download it, just keep somewhere a mapping of URL's to filenames.

Kendall Helmstetter Gelner