使用NSoperation多線程非同步載入圖片資料

來源:互聯網
上載者:User

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;//附帶的參數;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.