使用NSoperation多线程异步加载图片数据

本文介绍如何利用NSOperation类实现iOS平台上的并发下载图片功能,包括定义ImageDownloader类,实现关键方法,并通过NSOperationQueue进行任务调度。示例代码展示了初始化、下载流程、数据接收及处理过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;//附带的参数;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值