Friday, September 16, 2011

Subclass NSURLConnection

My recent work involves change two synchronous NSURLConnection to asynchronous, so loading data won't block UI.

I created a custom subclass of NSURLConnection to do this, with a tag I just need to specific the name of that connection at the time I created it, and then checking it while I receive data.

Here's the code:

.h file:

#import <Foundation/Foundation.h>

@interface CustomURLConnection : NSURLConnection {
NSString *tag;
}

@property (nonatomic, retain) NSString *tag;

- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOL)startImmediately tag:(NSString*)tag;
- (NSString *)tag;

@end

.m file:

#import "CustomURLConnection.h"

@implementation CustomURLConnection

@synthesize tag;

- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOL)startImmediately tag:(NSString*)newTag {
self = [super initWithRequest:request delegate:delegate startImmediately:startImmediately];
if (self) {
self.tag = newTag;
}
return self;
}

- (void)dealloc {
[tag release];
[super dealloc];
}

- (NSString *)tag {
return tag;
}

@end

And I used it like this:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
ALog(@"Connection %@ received data.", [(CustomURLConnection *)connection tag]);
if ([[(CustomURLConnection *)connection tag] isEqualToString:@"someConnection"]) {
[someData appendData:data];
}
else if ([[(CustomURLConnection *)connection tag] isEqualToString:@"someOtherConnection"]) {
[someOtherData appendData:data];
}
}

No comments:

Post a Comment