使用NSOperation建立多任务网络连接
来源:互联网 发布:战舰世界 青叶 数据 编辑:程序博客网 时间:2024/04/30 19:36
首先准备一个 NSOperation 的子类,用于处理 HTTP 请求。
@interface RequestOperation : NSOperation {
NSURLRequest* _request;
NSMutableData* _data;
}
- (id)initWithRequest:(NSURLRequest *)request;
@end
下面是实现:
@implementation RequestOperation
- (id)initWithRequest:(NSURLRequest *)request {
if (self = [self init]) {
_request = [request retain];
_data = [[NSMutableData data] retain];
}
return self;
}
- (void)dealloc {
[_request release];
[_data release];
[super dealloc];
}
// 如果不载下面的函数,会出错
- (BOOL)isConcurrent {
return YES;
}
// 开始处理
- (void)start {
if (![self isCancelled]) {
// 以异步方式处理事件
[NSURLConnection connectionWithRequest:_request delegate:self];
}
}
// 取得数据
- (void)connection:(NSURLConnection*)connection
didReceiveData:(NSData*)data {
// 添加数据
[_data appendData:data];
}
// HTTP请求结束
- (void)connectionDidFinishLoading:(NSURLConnection*)connection {
}
@end
如果没有重载 isConcurrent 函数,缺省是返回NO,就是说只能以同步的方式处理。而如果又使用了connectionWithRequest:delegate: 以异步方式处理事件后,会产生下面的错误信息:
1
_NSAutoreleaseNoPool(): Object 0x18a140 of class NSURLConnection autoreleased with no pool in place - just leaking
然后在你的 Controller 类中用 NSOperationQueue 来处理各个任务。
@interface xxViewController : UIViewController {
NSOperationQueue* _queue;
}
@end
@implementation xxViewController
- (IBAction)buttonClicked:(id) sender {
_queue = [[NSOperationQueue alloc] init];
// 第一个请求
NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com"]];
RequestOperation* operation = [[RequestOperation alloc] initWithRequest:request];
[operation autorelease];
// 第二个请求
NSURLRequest* request2 = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.yahoo.co.jp"]];
RequestOperation* operation2 = [[RequestOperation alloc] initWithRequest:request2];
[operation2 autorelease];
// 开始处理
[_queue addOperation:operation];
}
@end
以上,用 NSOperation 来并行处理不同的任务,使用 NSOperationQueue 来控制复数的 NSOperation,并且可以限制Queue的大小,而不是无限制的使用任务。当一个任务完成,就执行待机中的任务。
- 使用NSOperation建立多任务网络连接
- iPhone开发技巧之网络篇(3)--- 使用NSOperation建立多任务网络连接
- NSOperation封装- 多任务下载
- 使用Socket建立网络连接TCP版
- http建立网络连接
- Upd建立网络连接
- 网络多线程-NSOperation的简单使用
- Socket建立网络连接方法
- mac建立PPPoe网络连接
- NSOperation使用
- NSOperation使用
- NSOperation使用
- NSOperation使用
- NSOperation+网络图片
- .Net网络编程——使用TcpClient与TcpListener建立客户端与服务端连接
- 网络IPC, socket(3): 建立连接
- Windows Mobile Emulator建立网络连接
- 利用 net use建立网络连接
- SQL Server 2005 学习笔记之触发器简介[转]
- BIS-BES对比
- UDP穿透NAT的原理与实现之P2P篇
- 控制并发访问的线程数 Semaphore 信号灯
- How property system works on Android
- 使用NSOperation建立多任务网络连接
- MySQL:如何编写daemon plugin
- MyEclipse设置代码提示功能
- JSP的隐式对象
- 文本偏移
- 设备管理器打不开——简单易行
- RandomAccessFile(转)
- 使用InetAddress 获取主机名注意!!!
- Android 特殊字符转义