iPhone开发应用中NSOperation多线程使用是本文要介绍的内容,首先创建一个线程类,RequestOperation,它继承NSOperation,而后我们在控制器类当中,创建一个NSOperationQueue对象,将该线成加入到序列中。它就会自动的从NSOperationQueue当中取到我们加入的线程,而后运行线成的start方法。
- #import "RootViewController.h"
- @implementation RootViewController
- #pragma mark -
- #pragma mark View lifecycle
- -(void)buttonClicked:(id)sender{
- _queue=[[NSOperationQueue alloc] init];
- //第一个请求
- NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http:www.google.com"]];
- RequestOperation *operation=[[RequestOperation alloc] initWithRequest:request];
- [_queue addOperation:operation];
- [operation release];
- //第二个请求
- //NSURLRequest *request2=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http:www.baidu.com"]];
- //RequestOperation *operation1=[[RequestOperation alloc]initWithRequest:request2];
- //operation1.message=@"operation1---";
- //[_queue addOperation:operation1];
- }
- #import <Foundation/Foundation.h>
- @interface RequestOperation : NSOperation{
- NSURLRequest *_request;
- NSMutableData *_data;
- NSString *message;
- }
- @property(nonatomic,retain)NSString *message;
- -(id)initWithRequest:(NSURLRequest*)request;
- @end
- //
- // RequestOperation.m
- // NSOperation
- //
- // Created by wangqiulei on 8/23/10.
- // Copyright 2010 __MyCompanyName__. All rights reserved.
- //
- #import "RequestOperation.h"
- @implementation RequestOperation
- @synthesize message;
- -(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];
- }
- //如果返回为YES表示asychronously方式处理
- -(BOOL)isConcurrent{
- return YES;
- }
- //开始处理
- -(void)start{
- if (![self isCancelled]) {
- NSLog(@"%@",self.message);
- NSLog(@"-------------%d",[self retainCount]);
- [NSURLConnection connectionWithRequest:_request delegate:self];
- }
- }
- //取得数据
- -(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
- //添加数据
- [_data appendData:data];
- NSLog(@"%@",_data);
- }
- //http请求结束
- -(void)connectionDidFinishLoading:(NSURLConnection *)connection{
- }
- @end
小结:iPhone开发应用中NSOperation多线程使用的内容介绍完了,希望通过本文的学习对你有所帮助!