使用NSOperation建立多任务网络连接
博主:易飞扬 原文链接?:?http://www.yifeiyang.net/iphone-web-development-skills-of-the-articles-3-use-a-multi-task-network-connection-nsoperation/ 转载请保留上面文字。
iPhone开发技巧之网络篇(3)--- 使用NSOperation建立多任务网络连接
在网络应用程序中,经常需要多任务连接来提高程序的性能。比如多任务下载,多任务HTTP请求等,即线程控制模型中的工作群模型。使用 NSOperation 可以很容易实现这个功能。下面就以使用NSOperation处理并行的HTTP请求为例子,说明其用法。
首先准备一个 NSOperation 的子类,用于处理 HTTP 请求。
1234567891011121314151617
@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的大小,而不是无限制的使用任务。当一个任务完成,就执行待机中的任务。