iOS开发笔记--异步加载UIImageView----AsyImageView

能够异步加载图片的UIImageView,通过调用方法loadImageWithUrl:与loadImageWithUrl:andDefaultImage:来进行异步加载。用到了NSCache、文件缓存、NSOperation、NSQueue来完成。首先是头文件的定义

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. //定义缓存地址的宏  
  2.   
  3. #define kCIVCache [NSHomeDirectory() stringByAppendingString:@"/Library/Caches/CIVCache.txt"]  

定义加载Operation接口

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. @protocol AsyImageLoadOperation <NSObject>  
  2. - (void)cancel;  
  3. @end  

定义单例队列Manager

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. @interface QueueManager : NSObject  
  2. +(id)sharedManager;  
  3. @property (nonatomic,retainNSOperationQueue *queue;  
  4. @end  

定义缓存模型

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. @interface CIVImageCache : NSObject  
  2. @property (strong,nonatomicNSURL *url;  
  3. @property (strong,nonatomicNSData *imageData;  
  4. @end  

定义图片加载Operation

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. @interface ImageLoadOperation : NSOperation<AsyImageLoadOperation>  
  2. -(id)initWithUrl:(NSURL *)url;  
  3. @property (nonatomic,strongNSURL *url;  
  4. @property (nonatomic,strongCIVImageCache *resultCache;  
  5. @end  

定义AsyImageView

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. @interface AsyImageView : UIImageView  
  2. -(void)loadImageWithUrl:(NSURL *)url;  
  3. -(void)loadImageWithUrl:(NSURL *)url andDefultImage:(UIImage *)image;  
  4. @end  

接着就是实现头文件,.m文件中需要引入

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #import "objc/runtime.h"  
  2. #include <sys/sysctl.h>  

定义静态的operationKey字符变量

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. static char operationKey;  

QueueManager的实现

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. @implementation QueueManager  
  2.   
  3. unsigned int countOfCores() {  
  4.     unsigned int ncpu;  
  5.     size_t len = sizeof(ncpu);  
  6.     sysctlbyname("hw.ncpu", &ncpu, &len, NULL0);  
  7.     return ncpu;  
  8. }  
  9.   
  10. static QueueManager *instance;  
  11. +(id)sharedManager{  
  12.     static dispatch_once_t onceToken;  
  13.     dispatch_once(&onceToken, ^{  
  14.         instance=[[QueueManager alloc] init];  
  15.     });  
  16.     return instance;  
  17. }  
  18.   
  19. -(id)init{  
  20.     self=[super init];  
  21.     if (self) {  
  22.         _queue=[[NSOperationQueue alloc] init];  
  23.         _queue.maxConcurrentOperationCount=countOfCores();  
  24.     }  
  25.     return self;  
  26. }  

countOfCores方法用来获取当前机器的CPU核数。在init初始化中初始化一个NSOperationQueue,并为这个队列指定最大并发操作数(最好是CPU有多少核就设置为多少的最大并发数)。单例的实现使用GCD的dispatch_once。

实现缓存模型对象

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. @implementation CIVImageCache   
  2.   
  3. -(id)init{  
  4.     self=[super init];  
  5.     if (self){  
  6.         _imageData=[[NSData alloc] init];  
  7.         _url=[[NSURL alloc] init];  
  8.     }  
  9.     return self;  
  10. }  
  11.   
  12. -(id)initWithCoder:(NSCoder *)aDecoder{  
  13.     self=[super init];  
  14.     if (self){  
  15.         _imageData  =   [aDecoder decodeObjectForKey:@"_imageData"];  
  16.         _url        =   [aDecoder decodeObjectForKey:@"_url"];  
  17.     }  
  18.     return self;  
  19. }  
  20.   
  21. -(void)encodeWithCoder:(NSCoder *)aCoder{  
  22.     [aCoder encodeObject:_imageData forKey:@"_imageData"];  
  23.     [aCoder encodeObject:_url forKey:@"_url"];  
  24. }  
  25.   
  26. -(id)copyWithZone:(NSZone *)zone{  
  27.     CIVImageCache *uObject=[[[self class] allocWithZone:zone] init];  
  28.     uObject.imageData=self.imageData;  
  29.     uObject.url=self.url;  
  30.     return uObject;  
  31. }  
  32.   
  33. @end  

这个没有什么好说的,这个对象主要用来在加载完成后传递数据以及将数据保存在本地。 接下来实现图片加载操作(ImageLoadOperation)

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. @implementation ImageLoadOperation  
  2.   
  3. -(id)initWithUrl:(NSURL *)url{  
  4.     self=[super init];  
  5.     if (self) {  
  6.         _url=url;  
  7.     }  
  8.     return self;  
  9. }  
  10.   
  11. -(void)main{  
  12.     NSData *cacheData=[NSData dataWithContentsOfFile:kCIVCache];  
  13.     NSDictionary *cacheDic=[NSKeyedUnarchiver unarchiveObjectWithData:cacheData];  
  14.     if (cacheDic!=nil) {  
  15.         if ([[cacheDic allKeys] containsObject:_url.description]) {  
  16.             CIVImageCache *cache=[[CIVImageCache alloc] init];  
  17.             cache.url=_url;  
  18.             cache.imageData=[cacheDic objectForKey:_url.description];  
  19.             _resultCache=cache;  
  20.         }else{  
  21.             [self loadFromInternet];  
  22.         }  
  23.     }else{  
  24.         [self loadFromInternet];  
  25.     }  
  26. }  
  27.   
  28. -(void)loadFromInternet{  
  29.     NSData *imageData=[NSData dataWithContentsOfURL:_url];  
  30.     UIImage *image=[UIImage imageWithData:imageData];  
  31.     imageData = UIImageJPEGRepresentation(image, 0.0000001);  
  32.     CIVImageCache *cache=[[CIVImageCache alloc] init];  
  33.     cache.url=_url;  
  34.     cache.imageData=imageData;  
  35.     _resultCache=cache;  
  36. }  
  37. @end  

main函数中为主要的加载操作,首先从本地缓存中获取数据,判断是否已经存在URL的请求缓存,如果没有调用loadFromInternet方法从网络下载图片。

最后来实现异步

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. @interface AsyImageView ()  
  2. @property (nonatomic,weak) NSOperation *lastOperation;  
  3. @property (strongnonatomicNSCache *memCache;  
  4. @property (assign, nonatomic) dispatch_queue_t ioQueue;  
  5. @end  

定义AsyImageView的“私有”变量,lastOperation用来关联operation的顺序(这个最后好像没有用到)memCache则用来进行缓存,ioQueue是用来缓存文件的操作队列。

AsyImageView使用两种初始化方法来初始化:

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. -(id)init{  
  2.     self=[super init];  
  3.     if (self) {  
  4.         _ioQueue = dispatch_queue_create("com.noez.AsyImageCache", DISPATCH_QUEUE_SERIAL);  
  5.         NSString *fullNamespace = [@"com.noez.AsyImageCache." stringByAppendingString:@"1"];  
  6.         _memCache = [[NSCache alloc] init];  
  7.         _memCache.name = fullNamespace;  
  8.     }  
  9.     return self;  
  10. }  
  11.   
  12. -(id)initWithFrame:(CGRect)frame{  
  13.     self=[super initWithFrame:frame];  
  14.     if (self) {  
  15.         _ioQueue = dispatch_queue_create("com.noez.AsyImageCache", DISPATCH_QUEUE_SERIAL);  
  16.         NSString *fullNamespace = [@"com.noez.AsyImageCache." stringByAppendingString:@"1"];  
  17.         _memCache = [[NSCache alloc] init];  
  18.         _memCache.name = fullNamespace;  
  19.     }  
  20.     return self;  
  21. }  

在AsyImageView中的layoutSubviews中也需要初始化ioQueue与memCache,如果是直接在XIB中直接设置AsyImageView的话并不会调用两个初始化方法。

loadImageWithUrl方法中开始异步的加载过程:

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. -(void)loadImageWithUrl:(NSURL *)url{  
  2.     [self cancelCurrentImageLoad];  
  3.     NSOperationQueue *queue=[[QueueManager sharedManager] queue];  
  4.     __weak AsyImageView *weakSelf=self;  
  5.     id<AsyImageLoadOperation> operation=[self downloadWithURL:url queue:queue completed:^(UIImage *image, NSData *data, NSError *error, BOOL isFinished) {  
  6.         void (^block)(void) = ^{  
  7.             __strong AsyImageView *sself = weakSelf;  
  8.             if (!sself) return;  
  9.             if (image){  
  10.                 sself.image = image;  
  11.                 [sself setNeedsLayout];  
  12.             }  
  13.         };  
  14.         if ([NSThread isMainThread]){  
  15.             block();  
  16.         }  
  17.         else{  
  18.             dispatch_sync(dispatch_get_main_queue(), block);  
  19.         }  
  20.     }];  
  21.     objc_setAssociatedObject(self, &operationKey, operation, OBJC_ASSOCIATION_RETAIN_NONATOMIC);  
  22. }  

在这个方法中首先调用cancelCurrentImageLoad来取消当前的加载操作:

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. - (void)cancelCurrentImageLoad  
  2. {  
  3.     // Cancel in progress downloader from queue  
  4.     id<AsyImageLoadOperation> operation = objc_getAssociatedObject(self, &operationKey);  
  5.     if (operation)  
  6.     {  
  7.         [operation cancel];  
  8.         objc_setAssociatedObject(self, &operationKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);  
  9.     }  
  10. }  

之后获取单例的操作队列后调用downloadWithURL方法开始异步加载,加载完之后通过block将图片赋值给image属性。

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. -(id<AsyImageLoadOperation>)downloadWithURL:(NSURL *)url queue:(NSOperationQueue *)queue completed:(void (^)(UIImage *image, NSData *data, NSError *error, BOOL isFinished))completedBlock{  
  2.     ImageLoadOperation *op=[[ImageLoadOperation alloc] init];  
  3.     [self queryDiskCacheForKey:url.description done:^(UIImage *image) {  
  4.         if (image==nil) {  
  5.             op.url=url;  
  6.             __weak ImageLoadOperation *weakOp=op;  
  7.             op.completionBlock=^{  
  8.                 CIVImageCache *cache=weakOp.resultCache;  
  9.                 UIImage *dimage=[UIImage imageWithData:cache.imageData];  
  10.                 completedBlock(dimage,nil,nil,YES);  
  11.                 [self storeImage:dimage imageData:cache.imageData forKey:cache.url.description toDisk:YES];  
  12.             };  
  13.             [self.lastOperation addDependency:op];//待定  
  14.             self.lastOperation=op;  
  15.             [queue addOperation:op];  
  16.         }else{  
  17.             completedBlock(image,nil,nil,YES);  
  18.         }  
  19.     }];  
  20.     return op;  
  21. }  

在加载前首先调用queryDiskCacheForKey方法从缓存中获取图片,如果缓存中没有图片,则使用图片加载操作加载图片,在操作完成时使用block保存图片并调用completedBlock显示图片。如果缓存中有图片则直接调用completedBlock显示图片。一下分别是保存图片与从缓存获取图片的方法:

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. - (void)storeImage:(UIImage *)image imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk{  
  2.     if (!image || !key){  
  3.         return;  
  4.     }  
  5.   
  6.     [self.memCache setObject:image forKey:key cost:image.size.height * image.size.width * image.scale];  
  7.   
  8.     if (toDisk){  
  9.         dispatch_async(self.ioQueue, ^{  
  10.                            NSData *data = imageData;  
  11.   
  12.                            if (!data){  
  13.                                if (image){  
  14.                                    data = UIImageJPEGRepresentation(image, (CGFloat)1.0);  
  15.                                }  
  16.                            }  
  17.                            if (data){  
  18.                                NSData *cacheData=[NSData dataWithContentsOfFile:kCIVCache];  
  19.                                if (cacheData==nil) {  
  20.                                    cacheData=[[NSData alloc] init];  
  21.                                }  
  22.                                NSMutableDictionary *dic=[NSKeyedUnarchiver unarchiveObjectWithData:cacheData];  
  23.                                if (dic==nil) {  
  24.                                    dic=[[NSMutableDictionary alloc] init];  
  25.                                }  
  26.                                if (![[dic allKeys] containsObject:key]) {  
  27.                                    [dic setObject:data forKey:key];  
  28.                                }  
  29.                                NSData *data=[NSKeyedArchiver archivedDataWithRootObject:dic];  
  30.                                [data writeToFile:kCIVCache atomically:YES];  
  31.                            }  
  32.                        });  
  33.     }  
  34. }  
  35.   
  36. - (void)queryDiskCacheForKey:(NSString *)key done:(void (^)(UIImage *image))doneBlock{  
  37.     if (!doneBlock) return;  
  38.     if (!key){  
  39.         doneBlock(nil);  
  40.         return;  
  41.     }  
  42.   
  43.     UIImage *image = [self imageFromMemoryCacheForKey:key];  
  44.     if (image){  
  45.         doneBlock(image);  
  46.         return;  
  47.     }  
  48.     if (_ioQueue==nil) {  
  49.         _ioQueue = dispatch_queue_create("com.noez.AsyImageCache", DISPATCH_QUEUE_SERIAL);  
  50.     }  
  51.     dispatch_async(self.ioQueue, ^{  
  52.                        @autoreleasepool{  
  53.                            UIImage *diskImage = [self diskImageForKey:key];  
  54.                            if (diskImage){  
  55.                                CGFloat cost = diskImage.size.height * diskImage.size.width * diskImage.scale;  
  56.                                [self.memCache setObject:diskImage forKey:key cost:cost];  
  57.                            }  
  58.   
  59.                            dispatch_async(dispatch_get_main_queue(), ^{  
  60.                                               doneBlock(diskImage);  
  61.                                           });  
  62.                        }  
  63.                    });  
  64. }  
  65.   
  66. - (UIImage *)imageFromMemoryCacheForKey:(NSString *)key {  
  67.     return [self.memCache objectForKey:key];  
  68. }  

转自: http://segmentfault.com/a/1190000000313657?page=1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值