非同期にデータを受信したあとコールバック関数で処理する

NetConnection.h

#import <Foundation/Foundation.h>

@interface NetConnection : NSObject {
    NSURLConnection *connection;
    NSMutableData *data;
    id object;
    SEL selector;
}

- (void)initWithURL:(NSString *)url object:(id)object_ selector:(SEL)selector_;
@end

NetConnection.m

#import "NetConnection.h"
#import<objc/runtime.h>

@implementation NetConnection
- (void)abort
{
    if (connection != nil) {
	[connection cancel];
	[connection release];
    }
    if (data != nil) {
	[data release];
    }
}

- (void)dealloc
{
    [self abort];
    [super dealloc];
}

- (void)initWithURL:(NSString *)url object:(id)object_ selector:(SEL)selector_
{
    [super init];
    
    object = object_;
    selector = selector_;
    data = [[NSMutableData alloc] initWithCapacity:0];
    
    NSURLRequest *req = [NSURLRequest 
			    requestWithURL:[NSURL URLWithString:url]
			    cachePolicy:NSURLRequestUseProtocolCachePolicy
			    timeoutInterval:30.0];
    
    connection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [data setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)nsdata
{
    [data appendData:nsdata];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [self abort];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    Method method = class_getInstanceMethod([object class], selector);
    IMP callback = method_getImplementation(method);
    
    callback(object, selector, data);
    [self abort];
}
@end

コールバック関数

- (void)callback:(NSData *)data
{
    NSString *str= [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%@", str);
}

呼び出し

[[NetConnection alloc] initWithURL:@"http://www.example.com/" object:self selector:@selector(callback:)];