异步加载图片是IOS软件开发中经常用到的 下面便是一些具体的步骤与方法 希望可以帮到不懂的同学们 注意:这是在MRC环境下
自己封装一个图片下载的类 方便使用
在ImageDownload.h文件中写入定义与声明
@class ImageDownload;
//定义一个名叫SuccessBlock的block
typedef void(^SuccessBlock)(ImageDownload *imageDownload, UIImage *image);
//定义一个名叫ErrorBlock的block
typedef void(^ErrorBlock)(ImageDownload *imageDownload, NSError *error);
@interface ImageDownload : NSObject
// 定义block为属性的时候 一定要用copy 原因在于 block定义完后 本身是在栈区或者全局区,不在堆区。当定义成属性的时候,需要copy一下 将其拷贝到堆区
@property (nonatomic, copy) SuccessBlock successBlock;
@property (nonatomic, copy) ErrorBlock errorBlock;
// 初始化方法,需要外界提供对应的网址
- (instancetype)initWithURLStr:(NSString *)urlStr;
// 便利构造器方法 方便外界使用
+ (ImageDownload *)imageDownloadWithURLStr:(NSString *)urlStr;
@end
在ImageDownload.m文件中写下对应的实现方法
@interface ImageDownload ()<NSURLConnectionDataDelegate>
@property (nonatomic, retain)NSMutableData *receiveData;// 在延展里面定义一个属性用来存放下载的数据
@end
@implementation ImageDownload
- (void)dealloc
{
[_receiveData release];
// 对Block类型的变量进行释放
Block_release(_successBlock);
Block_release(_errorBlock);
[super dealloc];
}
-(NSMutableData *)receiveData
{
if (_receiveData == nil) {
self.receiveData = [NSMutableData dataWithCapacity:0];
}
return _receiveData;
}
// 初始化方法,需要外界提供对应的网址
- (instancetype)initWithURLStr:(NSString *)urlStr
{
self = [super init];
if (self) {
NSURL *url = [NSURL URLWithString:urlStr];
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:15];
[[[NSURLConnection alloc]initWithRequest:request delegate:self] autorelease];
}
return self;
}
// 便利构造器方法 方便外界使用
+ (ImageDownload *)imageDownloadWithURLStr:(NSString *)urlStr
{
ImageDownload *imageDownload = [[ImageDownload alloc]initWithURLStr:urlStr ];
return [imageDownload autorelease];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// 拼接数据
[self.receiveData appendData:data];
}
// block的调用
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
UIImage *image = [UIImage imageWithData:self.receiveData];
self.successBlock(self,image);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
self.errorBlock(self,error);
}
@end
这样 自己封装的ImageDownload类就完成了 给外界提供了便利构造器的接口 可以使用
下面 就要开始我们的异步加载了 敬请期待。。。