转载请注明出处,原文网址:http://blog.csdn.net/m_changgong/article/details/8238093 作者:张燕广
实现的功能:1)演示多线程NSOperation&NSOperationQueue开发;2)子线程中执行下载图片工作,图片下载完成前显示等待框和下载进度条;
关键词:多线程 NSOperation NSOperationQueue 等待框
1、新建视图控制器ViewController(不带xib),作为根视图控制器,通过ViewController的-(void)loadView方法构建UI。
2、新建继承自NSOperation且实现协议NSURLConnectionDelegate的类DownLoadImageTask,DownLoadImageTask.h如下:
- #import <Foundation/Foundation.h>
- @protocol DownLoadImageDelegate;
- @interface DownLoadImageTask : NSOperation<NSURLConnectionDelegate>{
- int operationId;
- long long totalLength;
- BOOL done;
- }
- @property int operationId;
- @property(nonatomic,assign) id<DownLoadImageDelegate>downloadImageDelegate;
- @property(nonatomic,retain) NSMutableData *buffer;
- @property(nonatomic,retain) NSURLRequest *request;
- @property(nonatomic,retain) NSURLConnection *connection;
- - (id)initWithURLString:(NSString *)url;
- @end
- @protocol DownLoadImageDelegate
- //图片下载完成的委托
- -(void)imageDownLoadFinished:(UIImage *)img;
- //更新图片下载进度条的值
- -(void)updateDownProgress:(double) value;
- @end
DownLoadImageTask.m如下:
- <span style="font-family:Microsoft YaHei;font-size:18px;">#import "DownLoadImageTask.h"
- @implementation DownLoadImageTask
- @synthesize operationId;
- @synthesize downloadImageDelegate;
- @synthesize buffer;
- @synthesize request;
- @synthesize connection;
- - (id)initWithURLString:(NSString *)url{
- NSLog(@"url=%@",url);
- self = [super init];
- if(self){
- request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
- buffer = [NSMutableData data];
- }
- return self;
- }
- //主要处理方法
- -(void)start{ //或者main
- NSLog(@"DownLoadImageTask-start");
- if(![self isCancelled]){
- //暂停一下
- [NSThread sleepForTimeInterval:1];
- //设置connection及其代理
- connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
- if(connection!=nil){
- while(!done){
- [[NSRunLoop currentRunLoop]runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
- }
- }
- }
- }
- -(void)httpConnectEndWithError{
- //[self hiddenWaiting];
- NSLog(@"httpConnectEndWithError");
- }
- -(void)dealloc{
- buffer = nil;
- connection = nil;
- request = nil;
- downloadImageDelegate = nil;
- }
- #pragma NSURLConnection delegate methods
- //不执行缓存
- -(NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse{
- return nil;
- }
- //连接发生错误
- -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
- [self performSelectorOnMainThread:@selector(httpConnectEndWithError) withObject:self waitUntilDone:NO];
- [buffer setLength:0];
- }
- //收到响应
- - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
- NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
- if(httpResponse && [httpResponse respondsToSelector:@selector(allHeaderFields)]){
- NSDictionary *httpResponseHeaderFields = [httpResponse allHeaderFields];
- totalLength = [[httpResponseHeaderFields objectForKey:@"Content-Length"] longLongValue];
- NSLog(@"totalLength is %lld",totalLength);
- }
- }
- //接收数据
- -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
- //NSLog(@"didReceiveData...");
- [buffer appendData:data];
- double progressValue = totalLength==0?0:((double)([buffer length])/(double)totalLength);
- //更新进度条值
- [downloadImageDelegate updateDownProgress:progressValue];
- }
- //下载完毕
- -(void)connectionDidFinishLoading:(NSURLConnection *)connection{
- done = YES;
- UIImage *img = [[UIImage alloc] initWithData:buffer];
- [downloadImageDelegate imageDownLoadFinished:img];
- }
- -(BOOL)isConcurrent {
- //返回yes表示支持异步调用,否则为支持同步调用
- return YES;
- }
- - (BOOL)isExecuting{
- return connection == nil;
- }
- - (BOOL)isFinished{