一个下载操作就交给一个HMDownloadOperation对象

HMDownloadOperation.h / .m

@class HMDownloadOperation;

@protocol HMDownloadOperationDelegate <NSObject>
@optional
- (void)downloadOperation:(HMDownloadOperation *)operation didFinishDownload:(UIImage *)image;
@end @interface HMDownloadOperation : NSOperation
@property (nonatomic, copy) NSString *url;
@property (nonatomic, strong) NSIndexPath *indexPath;
@property (nonatomic, weak) id<HMDownloadOperationDelegate> delegate;
@end
#import "HMDownloadOperation.h"

@implementation HMDownloadOperation

/**
* 在main方法中实现具体操作
*/
- (void)main
{
@autoreleasepool { NSURL *downloadUrl = [NSURL URLWithString:self.url];
NSData *data = [NSData dataWithContentsOfURL:downloadUrl]; // 这行会比较耗时
UIImage *image = [UIImage imageWithData:data]; if ([self.delegate respondsToSelector:@selector(downloadOperation:didFinishDownload:)]) {
dispatch_async(dispatch_get_main_queue(), ^{ // 回到主线程, 传递图片数据给代理对象
[self.delegate downloadOperation:self didFinishDownload:image];
});
}
}
}

控制器View 调用

@interface HMViewController () <HMDownloadOperationDelegate>
@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 HMViewController - (NSArray *)apps
{
if (!_apps) {
NSArray *dictArray = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"apps.plist" ofType:nil]]; NSMutableArray *appArray = [NSMutableArray array];
for (NSDictionary *dict in dictArray) {
HMApp *app = [HMApp appWithDict:dict];
[appArray addObject:app];
}
_apps = appArray;
}
return _apps;
} - (NSOperationQueue *)queue
{
if (!_queue) {
_queue = [[NSOperationQueue alloc] init];
_queue.maxConcurrentOperationCount = ; // 最大并发数 == 3
}
return _queue;
} - (NSMutableDictionary *)operations
{
if (!_operations) {
_operations = [NSMutableDictionary dictionary];
}
return _operations;
} - (NSMutableDictionary *)images
{
if (!_images) {
_images = [NSMutableDictionary dictionary];
}
return _images;
} - (void)viewDidLoad
{
[super viewDidLoad]; } #pragma mark - 数据源方法
- (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:UITableViewCellStyleSubtitle reuseIdentifier:ID];
} HMApp *app = self.apps[indexPath.row];
cell.textLabel.text = app.name;
cell.detailTextLabel.text = app.download; // 显示图片
// 保证一个url对应一个HMDownloadOperation
// 保证一个url对应UIImage对象 UIImage *image = self.images[app.icon];
if (image) { // 缓存中有图片
cell.imageView.image = image;
} else { // 缓存中没有图片, 得下载
cell.imageView.image = [UIImage imageNamed:@"57437179_42489b0"]; HMDownloadOperation *operation = self.operations[app.icon];
if (operation) { // 正在下载
// ... 暂时不需要做其他事 } else { // 没有正在下载
// 创建操作
operation = [[HMDownloadOperation alloc] init];
operation.url = app.icon;
operation.delegate = self;
operation.indexPath = indexPath;
[self.queue addOperation:operation]; // 异步下载 self.operations[app.icon] = operation;
}
} // SDWebImage : 专门用来下载图片
return cell;
} #pragma mark - HMDownloadOperationDelegate
- (void)downloadOperation:(HMDownloadOperation *)operation didFinishDownload:(UIImage *)image
{
// 1.移除执行完毕的操作
[self.operations removeObjectForKey:operation.url]; if (image) {
// 2.将图片放到缓存中(images)
self.images[operation.url] = image; // 3.刷新表格
[self.tableView reloadRowsAtIndexPaths:@[operation.indexPath] withRowAnimation:UITableViewRowAnimationNone]; // 3.将图片写入沙盒
// NSData *data = UIImagePNGRepresentation(image);
// [data writeToFile:@"" atomically:<#(BOOL)#>];
} } - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
// 开始拖拽
// 暂停队列
[self.queue setSuspended:YES];
} - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
[self.queue setSuspended:NO];
} @end

IOS 自定义Operation(下载功能)的更多相关文章

  1. iOS多线程自定义operation加载图片 不重复下载图片

    摘要:1:ios通过抽象类NSOperation封装了gcd,让ios的多线程变得更为简单易用:   2:耗时的操作交给子线程来完成,主线程负责ui的处理,提示用户的体验   2:自定义operati ...

  2. iOS开发中文件的上传和下载功能的基本实现-备用

    感谢大神分享 这篇文章主要介绍了iOS开发中文件的上传和下载功能的基本实现,并且下载方面讲到了大文件的多线程断点下载,需要的朋友可以参考下 文件的上传 说明:文件上传使用的时POST请求,通常把要上传 ...

  3. ios开发视频播放后台下载功能实现 :1,ios播放视频 ,包含基于AVPlayer播放器,2,实现下载,iOS后台下载(多任务同时下载,单任务下载,下载进度,下载百分比,文件大小,下载状态)(真机调试功能正常)

    ABBPlayerKit ios开发视频播放后台下载功能实现 : 代码下载地址:https://github.com/niexiaobo/ABBPlayerKit github资料学习和下载地址:ht ...

  4. iOS彩票项目--第五天,新特性引导页的封装、返回按钮的自定义、导航控制器的滑动返回以及自定义滑动返回功能

    一.上次实现了在AppDelegate中通过判断app版本决定是否进入新特性页面,今天将AppDelegate中的一坨进行了封装.将self.window的根控制器到底应该为新特性界面,还是主页面,封 ...

  5. iOS项目开发常用功能静态库

    YHDeveloperTools iOS项目开发常用功能静态库 查看源码 功能方法: 1.字符检查 [NSString checkStringWithType:Email andTargetStrin ...

  6. iOS 自定义转场动画

    代码地址如下:http://www.demodashi.com/demo/12955.html 一.总效果 本文记录分享下自定义转场动画的实现方法,具体到动画效果:新浪微博图集浏览转场效果.手势过渡动 ...

  7. iOS自定义转场动画实战讲解

    iOS自定义转场动画实战讲解   转场动画这事,说简单也简单,可以通过presentViewController:animated:completion:和dismissViewControllerA ...

  8. iOS之开发支付功能概述

    前言:本随笔将对IOS开发的支付功能进行一个概述. 内容大纲: 一.常见的支付方案简介 二.第三方支付SDK 三.苹果官方支付方案 四.Web支付方案 正文: 一.常见的支付方案简介 在微信支付中 微 ...

  9. IOS开发之支付功能概述

    前言:本随笔将对IOS开发的支付功能进行一个概述. 内容大纲: 一.常见的支付方案简介 二.第三方支付SDK 三.苹果官方支付方案 四.Web支付方案 正文: 一.常见的支付方案简介 在微信支付中 微 ...

随机推荐

  1. linux安装php7

    之前一直对linux研究的比较少,终于下定决心好好把linux玩一下 首先~我是安装了vm虚拟机,然后使用的是centos7的版本.因为vm不好复制粘贴,故使用了xshell连接了我的linux进行操 ...

  2. Windows Server2008服务器可以远程桌面,但在内网中却Ping不通--解决方法

    Windows Server2008服务器可以通过远程桌面登录,但在内网中却Ping不通.所以要考虑的是防火墙是不是做了限制. 最简单粗暴的方法是直接把防火墙给关掉 还有个其他的方法是参考别人写的,我 ...

  3. java生成复杂word文档

    在Web应用中,有时需要按照固定的模板将数据导出到Word,如流程审批单,在流程处理完成后将处理过程按照流程单的要求导出,有时程序中需要实现生成 标准Word文档,要求能够打印,并且保持页面样式不变, ...

  4. PS使模糊图片变清晰

    操作步骤 \(文件\)

  5. maya安装错误

    AUTODESK系列软件着实令人头疼,安装失败之后不能完全卸载!!!(比如maya,cad,3dsmax等).有时手动删除注册表重装之后还是会出现各种问题,每个版本的C++Runtime和.NET f ...

  6. maya卸载不干净

    AUTODESK系列软件着实令人头疼,安装失败之后不能完全卸载!!!(比如maya,cad,3dsmax等).有时手动删除注册表重装之后还是会出现各种问题,每个版本的C++Runtime和.NET f ...

  7. fuser解决The requested resource is busy

    AIX 下出现umount busy | 处理  2011-08-17 17:22:57|  分类: AIX|字号 订阅如果一个文件系统打开了一个文件,那么必须在卸载之前将该文件关闭.例如:# umo ...

  8. jemeter的简单使用

    建立测试计划 启动jmeter后,jmeter会自动生成一个空的测试计划,用户可以基于该测试计划建立自己的测试计划. 添加线程组 一个性能测试请求负载是基于一个线程组完成的.一个测试计划必须有一个线程 ...

  9. WPF调用Win Form

    WPF是win form的下一代版本,现在越来越多的公司使用WPF.如何兼容已有的使用win form开发的应用程序呢?下面有三种方式来在WPF中调用win form. 使用WPF中的WindowsF ...

  10. ZK使用

    1. 关注问题 1. zookeeper集群如何保证请求的均匀分布? 由client建立连接时会随机取server保证均匀分布, 2.已布置完成的ZK集群如何扩容? 修改配置后逐台重启即可 2. ZK ...