NSoperation是ios封裝好的的實現多線程的很簡單的一種方法。
定義ImageDownloader ,這個類繼承NSOperation,因為需要並發,需要實現下面4個方法 :
//是否允許並發,-(BOOL)isConcurrent ;-(BOOL)isExecuting;
//是否已經完成,這個必須要重載,不然放在NSOperationQueue裡的NSOpertaion不能正常釋放。- (BOOL)isFinished//具體下載的方法在這裡執行。
- (void)start
而對應於非並發的情況下,只需要重載main方法就好了。
標頭檔
ImageDownloader.h
定義如下:
#import <Foundation/Foundation.h>@protocol imageDownloaderDelegate;@interface ImageDownloader : NSOperation { NSURLRequest* _request; NSURLConnection* _connection; NSMutableData* _data;//請求的資料 BOOL _isFinished; id<imageDownloaderDelegate> delegate; NSObject *delPara;//可攜帶額外的參數}- (id)initWithURLString:(NSString *)url;@property (readonly) NSData *data;@property(nonatomic, assign) id<imageDownloaderDelegate> delegate;@property(nonatomic, retain) NSObject *delPara;@end@protocol imageDownloaderDelegate@optional//圖片下載完成的代理方法- (void)imageDidFinished:(UIImage *)image para:(NSObject *)obj;@end
實現檔案
ImageDownloader.m
定義如下:
#import "ImageDownloader.h"@implementation ImageDownloader@synthesize data=_data;@synthesize delegate;@synthesize delPara;- (void)dealloc { [_request release]; _request=nil; [_data release]; _data=nil; [_connection release]; _connection=nil; [delPara release]; [super dealloc]; }- (id)initWithURLString:(NSString *)url { self = [self init]; if (self) { _request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url]]; _data = [[NSMutableData data] retain]; } return self; }// 開始處理-本類的主方法- (void)start { if (![self isCancelled]) { [NSThread sleepForTimeInterval:3]; // 以非同步方式處理事件,並設定代理 _connection=[[NSURLConnection connectionWithRequest:_request delegate:self]retain]; while(_connection != nil) { [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]; } } }#pragma mark NSURLConnection delegate Method// 接收到資料(增量)時- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data { // 添加資料 [_data appendData:data]; }- (void)connectionDidFinishLoading:(NSURLConnection*)connection { [_connection release], _connection=nil; NSLog(@"%s", __func__); UIImage *img = [[[UIImage alloc] initWithData:self.data] autorelease]; if (self.delegate != nil) { [delegate imageDidFinished:img para:self.delPara]; } }-(void)connection: (NSURLConnection *) connection didFailWithError: (NSError *) error{ [_connection release], _connection=nil; }-(BOOL)isConcurrent { //返回yes表示支援非同步呼叫,否則為支援同步調用 return YES; }- (BOOL)isExecuting{ return _connection == nil; }- (BOOL)isFinished{ return _connection == nil; }
應用舉例:
NSString *url =@”xxxxxxx“;
NSString*param=@”額外參數“;
ImageDownloader *downloader = [[[ImageDownloader alloc] initWithURLString:url] autorelease];
downloader.delegate = self;
downloader.delPara = param;
NSOperationQueue* queue = [[[NSOperationQueue alloc] init] autorelease];
[queue addOperation:downloader];
#pragma delegate
- (void)imageDidFinished:(UIImage *)image para:(NSObject *)obj
{
//image,下載下來的圖片;
NSString*param = (NSString *)obj;//附帶的參數;
}