我建议您查看有关 iPhone OS 中网络应用程序的 WWDC 会议。
- WWDC 2010 Session 207 - iPhone OS 的网络应用程序,第 1 部分
- WWDC 2010 Session 208 - iPhone OS 的网络应用程序,第 2 部分
讲师说
“线程是邪恶的™”
用于网络编程,建议使用带有 RunLoop 的异步网络编程。使用后台线程(Grand Central Dispatch Concurrent Queue)进行线程安全的数据处理,而不是用于网络编程。
顺便说一句,Blocks 和 Grand Central Dispatch 会议也值得一看。
- WWDC 2010 Session 206 - 在 iPhone 上介绍 Blocks 和 Grand Central Dispatch
- WWDC 2010 Session 211 - 使用 Grand Central Dispatch 简化 iPhone 应用程序开发
我为异步 NSURLConnection 编写了一个包装类。
AsyncURLConnection.h
#import <Foundation/Foundation.h>
typedef void (^completeBlock_t)(NSData *data);
typedef void (^errorBlock_t)(NSError *error);
@interface AsyncURLConnection : NSObject
{
NSMutableData *data_;
completeBlock_t completeBlock_;
errorBlock_t errorBlock_;
}
+ (id)request:(NSString *)requestUrl completeBlock:(completeBlock_t)completeBlock errorBlock:(errorBlock_t)errorBlock;
- (id)initWithRequest:(NSString *)requestUrl completeBlock:(completeBlock_t)completeBlock errorBlock:(errorBlock_t)errorBlock;
@end
AsyncURLConnection.m
#import "AsyncURLConnection.h"
@implementation AsyncURLConnection
+ (id)request:(NSString *)requestUrl completeBlock:(completeBlock_t)completeBlock errorBlock:(errorBlock_t)errorBlock
{
return [[[self alloc] initWithRequest:requestUrl
completeBlock:completeBlock errorBlock:errorBlock] autorelease];
}
- (id)initWithRequest:(NSString *)requestUrl completeBlock:(completeBlock_t)completeBlock errorBlock:(errorBlock_t)errorBlock
{
if ((self=[super init])) {
data_ = [[NSMutableData alloc] init];
completeBlock_ = [completeBlock copy];
errorBlock_ = [errorBlock copy];
NSURL *url = [NSURL URLWithString:requestUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection connectionWithRequest:request delegate:self];
}
return self;
}
- (void)dealloc
{
[data_ release];
[completeBlock_ release];
[errorBlock_ release];
[super dealloc];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[data_ setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[data_ appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
completeBlock_(data_);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
errorBlock_(error);
}
@end
如何使用 AsyncURLConnection 类。
/*
* AsyncURLConnection -request:completeBlock:errorBlock: have to be called
* from Main Thread because it is required to use asynchronous API with RunLoop.
*/
[AsyncURLConnection request:url completeBlock:^(NSData *data) {
/* success! */
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
/* process downloaded data in Concurrent Queue */
dispatch_async(dispatch_get_main_queue(), ^{
/* update UI on Main Thread */
});
});
} errorBlock:^(NSError *error) {
/* error! */
}];