多线程:简化自定义操作(模仿 SDWebImage)

#import "ViewController.h"
#import "DownLoadOperation.h"
//(此类在《 多线程:下载图片(不用SDWebImage)》中出现过)
#import "AppInfo.h" 

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (nonatomic, strong) NSOperationQueue *queue;
@property (nonatomic, copy) NSString *currentURL; // 记录当前下载的URL
@property (nonatomic, strong) NSMutableDictionary *operationCache; // 操作缓存池
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {


    NSArray *data = [AppInfo appInfoList];


    // 连续点击的时候,只显示最后一张
    AppInfo *app = data[arc4random_uniform(data.count)];

    // 判断要下载的URL跟上一个下载的URL的关系
    if (![app.icon isEqualToString:self.currentURL] && self.currentURL) {
        // 取出对应的操作
        DownLoadOperation *operation = self.operationCache[self.currentURL];
        // 取消上一个操作 (对cancal属性做一个标记)
        [operation cancel];

        // 移除操作
        [self.operationCache removeObjectForKey:self.currentURL];
    }

    self.currentURL = app.icon;
    // 创建操作
    DownLoadOperation *op = [DownLoadOperation downloadOperationWithURLString:app.icon finish:^(UIImage *image) {
//        NSLog(@"%@ -- %@",image,[NSThread currentThread]);
        self.imageView.image = image;

        // 下载完成之后也要移除操作
        [self.operationCache removeObjectForKey:app.icon];
    }];

    // 把操作添加到队列
    [self.queue addOperation:op];

    // 缓存操作
    [self.operationCache setObject:op forKey:app.icon];



}

- (NSMutableDictionary *)operationCache {
    if (_operationCache == nil) {
        _operationCache = [NSMutableDictionary dictionary];
    }
    return _operationCache;
}

- (IBAction)cancel:(id)sender {
    // 取消正在执行的操作 - 对所有的操作作一个取消的标记
    [self.queue cancelAllOperations];
    NSLog(@"%@",self.operationCache);
}
- (NSOperationQueue *)queue {
    if (_queue == nil) {
        _queue = [[NSOperationQueue alloc]init];
//        _queue.maxConcurrentOperationCount = 2;
    }
    return _queue;
}

@end
#import <UIKit/UIKit.h>

@interface DownLoadOperation : NSOperation

// 创建一个下载操作
+ (instancetype)downloadOperationWithURLString:(NSString *)URLString finish:(void(^)(UIImage *image))finish;


@end



#import "DownLoadOperation.h"
//(此类在《 多线程:下载图片(不用SDWebImage)》中出现过)
#import "NSString+Path.h"

@interface DownLoadOperation ()
// 图片下载的URLString
@property (nonatomic, copy) NSString *URLString;
// 下载完成之后的回调
@property (nonatomic, copy) void(^finish)(UIImage *image);
@end

@implementation DownLoadOperation
// 线程入口
- (void)main {
    // 需要添加自动释放池
    @autoreleasepool {
        // 断言 (只在debug模式下有作用)在上架之后不起作用
        NSAssert(self.finish != nil, @"完成回调不能为空");
        // 下载操作
        // 首先要有网址
        NSURL *url = [NSURL URLWithString:self.URLString];

        // 取出沙盒缓存
        NSString *path = [self.URLString appendCache];
        NSData *data = [NSData dataWithContentsOfFile:path];
        if (data) {
            // 直接回调
            [[NSOperationQueue mainQueue]addOperationWithBlock:^{
                NSLog(@"沙盒缓存");
                UIImage *image = [UIImage imageWithData:data];
                self.finish(image);
            }];
            return;
        }

        // 接收二进制数据
        data = [NSData dataWithContentsOfURL:url];

        // 如果有数据就保存图片
        if (data) {
            NSLog(@"%@",NSHomeDirectory());
            // 2. 沙盒缓存
            [data writeToFile:[self.URLString appendCache] atomically:YES];
        }

        // 关键节点判断 (耗时操作)
        if (self.isCancelled) {
            NSLog(@"操作已经被取消");
            // 操作已经被取消
            return;
        }


        UIImage *image = [UIImage imageWithData:data];
        // 完成之后的回调
        // 下载完成之后,回到主线程调用
        [[NSOperationQueue mainQueue]addOperationWithBlock:^{
            self.finish(image);
        }];


    }
}


+ (instancetype)downloadOperationWithURLString:(NSString *)URLString finish:(void (^)(UIImage *))finish {
    DownLoadOperation *op = [[self alloc]init];
    op.URLString = URLString;
    op.finish = finish;
    return op;
}

// SDWebImage 在start 方法中取消正在执行的操作 (已经提交了几千份代码)
// 不管操作是否已经被取消,都会调用 start 方法
// 如果重写start 方法来取消操作,很非常麻烦
// 有兴趣可以去看SDWebImage 的 start 方法
//- (void)start {
//    NSLog(@"cancel = %d",self.isCancelled);
//    if (self.isCancelled)return;
//
    NSLog(@"%s",__FUNCTION__);
//    [super start];
//
//}
@end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值