iPhone開(kāi)發(fā)應(yīng)用中NSOperation多線程使用
iPhone開(kāi)發(fā)應(yīng)用中NSOperation多線程使用是本文要介紹的內(nèi)容,首先創(chuàng)建一個(gè)線程類,RequestOperation,它繼承NSOperation,而后我們?cè)诳刂破黝惍?dāng)中,創(chuàng)建一個(gè)NSOperationQueue對(duì)象,將該線成加入到序列中。它就會(huì)自動(dòng)的從NSOperationQueue當(dāng)中取到我們加入的線程,而后運(yùn)行線成的start方法。
- #import "RootViewController.h"
- @implementation RootViewController
- #pragma mark -
- #pragma mark View lifecycle
- -(void)buttonClicked:(id)sender{
- _queue=[[NSOperationQueue alloc] init];
- //第一個(gè)請(qǐng)求
- NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http:www.google.com"]];
- RequestOperation *operation=[[RequestOperation alloc] initWithRequest:request];
- [_queue addOperation:operation];
- [operation release];
- //第二個(gè)請(qǐng)求
- //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;
- }
- //開(kāi)始處理
- -(void)start{
- if (![self isCancelled]) {
- NSLog(@"%@",self.message);
- NSLog(@"-------------%d",[self retainCount]);
- [NSURLConnection connectionWithRequest:_request delegate:self];
- }
- }
- //取得數(shù)據(jù)
- -(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
- //添加數(shù)據(jù)
- [_data appendData:data];
- NSLog(@"%@",_data);
- }
- //http請(qǐng)求結(jié)束
- -(void)connectionDidFinishLoading:(NSURLConnection *)connection{
- }
- @end
小結(jié):iPhone開(kāi)發(fā)應(yīng)用中NSOperation多線程使用的內(nèi)容介紹完了,希望通過(guò)本文的學(xué)習(xí)對(duì)你有所幫助!