自定义NSOperation Delegate文件下载内存沙盒缓存

注意:沙盒缓存应在ZYXDownloadOperation中完成封装不应该在代理中完成,后续完善

ZYXApp.h

#import <Foundation/Foundation.h>

@interface ZYXApp : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *download;
@property (nonatomic, copy) NSString *icon;        
+ (instancetype)appWithDict:(NSDictionary *)dict;
@end

ZYXApp.m

#import "ZYXApp.h"

@implementation ZYXApp
+ (instancetype)appWithDict:(NSDictionary *)dict
{
    ZYXApp *app = [[self alloc] init];
    [app setValuesForKeysWithDictionary:dict]; // KVC
    return app;
}
@end

ZYXDownloadOperation.h

#import <Foundation/Foundation.h>

@class ZYXDownloadOperation;


@protocol ZYXDownloadOperationDelegate <NSObject>
@optional
- (void)downloadOperation:(ZYXDownloadOperation *)operation didFinishDownloadWithImage:(UIImage *)image;
@end


@interface ZYXDownloadOperation : NSOperation
@property (nonatomic, copy) NSString *urlString;
@property (nonatomic, strong) NSIndexPath *indexPath;
@property (nonatomic, weak) id<ZYXDownloadOperationDelegate> delegate; // 代理对象属性使用weak
@end

ZYXDownloadOperation.m

#import "ZYXDownloadOperation.h"

@implementation ZYXDownloadOperation

/**
 *  自定义NSOperation的步骤很简单
 *  重写 - (void)main 方法,在里面实现想执行的任务
 */
- (void)main{
#warning - 自己创建自动释放池(因为如果是异步执行,无法访问主线程的自动释放池)
    @autoreleasepool{
        NSURL *downloadUrl  = [NSURL URLWithString:self.urlString];
        NSData *data = [NSData dataWithContentsOfURL:downloadUrl]; // 这行会比较耗时
        UIImage *image      = [UIImage imageWithData:data];
        if ([self.delegate respondsToSelector:@selector(downloadOperation:didFinishDownloadWithImage:)]){
            // 线程间通信,NSOperation和GCD的混合使用,子线程获取数据->主线程使用子线程获取的数据
            dispatch_async(dispatch_get_main_queue(), ^{ // 回到主线程, 传递图片数据给代理对象
                [self.delegate downloadOperation:self didFinishDownloadWithImage:image];
            });
        }
    }
}

@end

ViewController.m

#import "ViewController.h"

#import "ZYXApp.h"
#import "ZYXDownloadOperation.h"

@interface ViewController ()  <ZYXDownloadOperationDelegate>
@property (nonatomic, strong) NSArray *apps;
@property (nonatomic, strong) NSOperationQueue *queue;
/** key:url value:operation对象 */
@property (nonatomic, strong) NSMutableDictionary *operations;
/** key:url value:image对象*/
@property (nonatomic, strong) NSMutableDictionary *images;
@end

@implementation ViewController

#pragma mark - 懒加载
- (NSArray *)apps
{
    if (!_apps) {
        NSArray *dictArray = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"apps.plist" ofType:nil]];
        
        NSMutableArray *appArray = [NSMutableArray array];
        for (NSDictionary *dict in dictArray) {
            ZYXApp *app = [ZYXApp appWithDict:dict];
            [appArray addObject:app];
        }
        _apps = appArray;
    }
    return _apps;
}

- (NSOperationQueue *)queue
{
    if (!_queue) {
        _queue = [[NSOperationQueue alloc] init];
        // 最大并发数 == 3
        _queue.maxConcurrentOperationCount = 3;
    }
    return _queue;
}

- (NSMutableDictionary *)operations
{
    if (!_operations) {
        _operations = [NSMutableDictionary dictionary];
    }
    return _operations;
}

- (NSMutableDictionary *)images
{
    if (!_images) {
        _images = [NSMutableDictionary dictionary];
    }
    return _images;
}

#pragma mark - download task

#pragma mark - UITableViewDatasource 数据源方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.apps.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *ID = @"app";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                      reuseIdentifier:ID];
    }
    
    ZYXApp *app = self.apps[indexPath.row];
    cell.textLabel.text = app.name;
    cell.detailTextLabel.text = app.download;
    
    // 显示图片
    // 保证一个url对应一个ZYXDownloadOperation
    // 保证一个url对应UIImage对象
    
    UIImage *image = self.images[app.icon];
    if (image) { // 缓存中有图片
        cell.imageView.image = image;
    }
    else { // 缓存中没有图片, 看沙盒缓存是否有
        // 获得Library/Caches文件夹
        NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
        // 获得文件名
        NSString *filename = [app.icon lastPathComponent];
        // 计算出文件的全路径
        NSString *file = [cachesPath stringByAppendingPathComponent:filename];
        // 加载沙盒的文件数据
        NSData *data = [NSData dataWithContentsOfFile:file];
        
        if (data) { // 直接利用沙盒中图片
            UIImage *image = [UIImage imageWithData:data];
            cell.imageView.image = image;
            // 存到字典中
            self.images[app.icon] = image;
        }
        else { // 下载图片
            cell.imageView.image = [UIImage imageNamed:@"57437179_42489b0"];

            ZYXDownloadOperation *operation = self.operations[app.icon];
            if (operation) { // 正在下载
                // ... 暂时不需要做其他事
                
            } else { // 没有正在下载
                // 创建操作
                operation = [[ZYXDownloadOperation alloc] init];
                operation.urlString = app.icon;
                operation.delegate = self;
                operation.indexPath = indexPath;
                [self.queue addOperation:operation]; // 异步下载
                self.operations[app.icon] = operation;
            }
        }
    }
    
    // SDWebImage : 专门用来下载图片
    return cell;
}

#pragma mark - ZYXDownloadOperationDelegate 

- (void)downloadOperation:(ZYXDownloadOperation *)operation didFinishDownloadWithImage:(UIImage *)image{
    // 数据加载失败
    if (image == nil) {
        [self.operations removeObjectForKey:operation.urlString];
        return;
    }
    
    // 1.移除执行完毕的操作
    [self.operations removeObjectForKey:operation.urlString];
    
    if (image) {
        // 2.将图片放到缓存中(images)
        self.images[operation.urlString] = image;
        
        // 3.刷新表格
        [self.tableView reloadRowsAtIndexPaths:@[operation.indexPath]
                              withRowAnimation:UITableViewRowAnimationNone];

        // 4.将图片写入沙盒
        NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
        NSIndexPath *indexPath = operation.indexPath;
        ZYXApp *app = self.apps[indexPath.row];
        NSString *filename = [app.icon lastPathComponent];
        NSString *file = [cachesPath stringByAppendingPathComponent:filename];
        
        NSData *data = UIImagePNGRepresentation(image);
        [data writeToFile:file atomically:YES];
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    // 开始拖拽
    [self.queue setSuspended:YES];
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView
                     withVelocity:(CGPoint)velocity
              targetContentOffset:(inout CGPoint *)targetContentOffset{
    // 开始队列
    [self.queue setSuspended:NO];
}

@end

沙盒缓存.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,835评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,598评论 1 295
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,569评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,159评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,533评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,710评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,923评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,674评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,421评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,622评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,115评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,428评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,114评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,097评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,875评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,753评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,649评论 2 271

推荐阅读更多精彩内容