A caveat one quickly encounters when using multiple asynchronous NSURLConnections with the same target delegate is that there is no easy way to distinguish one connection from the other, in for instance the connection:didReceiveData: method.
Since using multiple asynchronous connections implies handling the received data chunks yourself, one is likely to create a dictionary which contains a NSMutableData object for each NSURLConnection key. Unfortunately does a NSDictionary copy its keys and this is not something a NSURLConnection supports. A quick solution to avoid this is to make a subclass with a tag to distinguish each connection. This tag can be used as key in the dictionary.
Interface:
@interface CustomURLConnection : NSURLConnection { NSString *tag; } @property (nonatomic, retain) NSString *tag; - (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOL)startImmediately tag:(NSString*)tag; @end
Implementation:
@implementation CustomURLConnection @synthesize tag; - (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOL)startImmediately tag:(NSString*)tag { self = [super initWithRequest:request delegate:delegate startImmediately:startImmediately]; if (self) { self.tag = tag; } return self; } - (void)dealloc { [tag release]; [super dealloc]; } @end
As you can see, creating a subclass with a tag property is rather easy and solves the dictionary issue.
Tags: NSURLConnection
Great tip!, thanks!
add this to implementation of CustomURLConnection
- (NSString *)tag {
return tag;
}
as if you try to get it by cURLConnectionvar.tag it gives error in didReceiveResponse and didReceiveData etc functions
so use [cURLConnectionvar tag]
gives a warning but should work
thanks for the code
What about using [NSValue valueWithNonRetainedObjectValue:] for the key? That would solve the issue as well.
hi, this is what I am really looking for, a multiple download method!!
I just see a light in the tunnel, but, my question is, how to add these codes to an UITableViewController ?
because in your example :
@interface CustomURLConnection : NSURLConnection {
NSString *tag;
}
it’s different to my app, how to implement this to my code below:
@interface LessonSubViewController : UITableViewController{
}
@end
any idea??
@Georg: You would create an instance of CustomURLConnection in the ViewDidLoad method of your LessonSubViewController controller. You would use this CustomURLConnection to load the data & once it is received update the table with the new data.
@Andreas Monitzer: I didn’t know that existed to be honest and it looks indeed like that could work. Thanks for bringing that up!
I just used an NSValue as the dictionary key, using the NSConnection pointer.:
+ (NSValue *)valueWithPointer:(const void *)pointer;