用NSOperation写下载队列
用NSOperation写下载队列

说明
1. 支持缓存机制
2. 图片都是在主线程中加载
3. 文件名用了md5加密
*这东西被人写烂了,但大伙如果对NSOperation不熟悉的话,可以看看本人的实现.
源码
https://github.com/YouXianMing/NSOperationExample
//
// ImageDownloadOperation.h
// NSOperationDownloadImage
//
// Created by YouXianMing on 15/9/7.
// Copyright (c) 2015年 YouXianMing. All rights reserved.
// #import <Foundation/Foundation.h>
@class ImageDownloadOperation; @protocol ImageDownloadOperationDelegate <NSObject> @required
- (void)imageDownloadOperation:(ImageDownloadOperation *)operation data:(NSData *)data; @end @interface ImageDownloadOperation : NSOperation { BOOL _executing;
BOOL _finished;
} /**
* 代理
*/
@property (nonatomic, weak) id <ImageDownloadOperationDelegate> delegate; /**
* 图片地址
*/
@property (nonatomic, strong) NSString *imageUrlString; /**
* 便利构造器
*
* @param urlString 图片地址
* @param delegate 代理
*
* @return 实例对象
*/
+ (instancetype)operationWithImageUrlString:(NSString *)urlString
delegate:(id <ImageDownloadOperationDelegate>)delegate; @end
//
// ImageDownloadOperation.m
// NSOperationDownloadImage
//
// Created by YouXianMing on 15/9/7.
// Copyright (c) 2015年 YouXianMing. All rights reserved.
// #import "ImageDownloadOperation.h"
#import <CommonCrypto/CommonDigest.h> @interface ImageDownloadOperation () @property (nonatomic, strong) NSURLConnection *connection;
@property (nonatomic, strong) NSString *md5String;
@property (nonatomic, strong) NSString *filePathString; @end @implementation ImageDownloadOperation - (void)main { // 验证图片地址是否为空
if (_imageUrlString.length <= ) { [self delegateEventWithData:nil];
[self completeOperation]; return;
} // 生成文件路径
self.md5String = [self MD5HashWithString:_imageUrlString];
self.filePathString = [self pathWithFileName:self.md5String]; // 文件如果存在则直接读取
BOOL exist = [[NSFileManager defaultManager] fileExistsAtPath:self.filePathString isDirectory:nil];
if (exist) { [self delegateEventWithData:[NSData dataWithContentsOfFile:self.filePathString]];
[self completeOperation]; return;
} NSURL *url = [NSURL URLWithString:_imageUrlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
self.connection = [NSURLConnection connectionWithRequest:request delegate:self]; // 让线程不结束
do { @autoreleasepool { [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; if (self.isCancelled) { [self completeOperation];
}
} } while (self.isExecuting && self.isFinished == NO);
} #pragma mark - 网络代理
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [self writeData:data toPath:self.filePathString];
[self delegateEventWithData:data];
} - (void)connectionDidFinishLoading:(NSURLConnection *)connection { [self completeOperation];
} - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { [self delegateEventWithData:nil];
[self completeOperation];
} #pragma mark -
+ (instancetype)operationWithImageUrlString:(NSString *)urlString
delegate:(id <ImageDownloadOperationDelegate>)delegate { ImageDownloadOperation *operation = [[ImageDownloadOperation alloc] init];
operation.delegate = delegate;
operation.imageUrlString = urlString; return operation;
} #pragma mark -
- (void)completeOperation { [self willChangeValueForKey:@"isFinished"];
[self willChangeValueForKey:@"isExecuting"];
_executing = NO;
_finished = YES;
[self didChangeValueForKey:@"isExecuting"];
[self didChangeValueForKey:@"isFinished"];
} - (void)start { if ([self isCancelled]) { [self willChangeValueForKey:@"isFinished"];
_finished = YES;
[self didChangeValueForKey:@"isFinished"]; return;
} [self willChangeValueForKey:@"isExecuting"];
[NSThread detachNewThreadSelector:@selector(main) toTarget:self withObject:nil];
_executing = YES;
[self didChangeValueForKey:@"isExecuting"];
} - (BOOL)isExecuting { return _executing;
} - (BOOL)isFinished { return _finished;
} - (BOOL)isConcurrent { return YES;
} #pragma mark -
- (NSString *)MD5HashWithString:(NSString *)string { CC_MD5_CTX md5; CC_MD5_Init(&md5);
CC_MD5_Update(&md5, [string UTF8String], (CC_LONG) [string length]); unsigned char digest[CC_MD5_DIGEST_LENGTH];
CC_MD5_Final(digest, &md5); NSString *s = [NSString stringWithFormat: @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
digest[], digest[],
digest[], digest[],
digest[], digest[],
digest[], digest[],
digest[], digest[],
digest[], digest[],
digest[], digest[],
digest[], digest[]]; return s;
} - (NSString *)pathWithFileName:(NSString *)name { NSString *path = [NSString stringWithFormat:@"/Documents/%@", name];
return [NSHomeDirectory() stringByAppendingPathComponent:path];
} - (void)delegateEventWithData:(NSData *)data { if (_delegate && [_delegate respondsToSelector:@selector(imageDownloadOperation:data:)]) { dispatch_async(dispatch_get_main_queue(), ^{ [_delegate imageDownloadOperation:self data:data];
});
}
} - (void)writeData:(NSData *)data toPath:(NSString *)path { dispatch_async(dispatch_get_global_queue(, ), ^{ [data writeToFile:path atomically:YES];
});
} @end
细节

用NSOperation写下载队列的更多相关文章
- Objective-c 多线程操作 自定义NSOperation 模拟下载
写在前面 使用多线程下载图片,使用内存缓存和磁盘缓存. 这里只为理解NSOperation及其派生类 真要应用到APP中 请下载成熟的第三方库 效果 下载多张图片时可控制线程并发数 分析 自定义NSO ...
- [翻译] 使用开源库 JGDownloadAcceleration 控制下载队列,断点下载,加速下载
JGDownloadAcceleration 本人对原文进行了翻译,凑合看看,使用心得以后补上 https://github.com/JonasGessner/JGDownloadAccelerati ...
- Java语言实现简单FTP软件------>上传下载队列窗口的实现(七)
1.首先看一下队列窗口的界面 2.看一下上传队列窗口的界面 3.看一下下载队列窗口的界面 4.队列窗口的实现 package com.oyp.ftp.panel.queue; import stati ...
- WorldWind源码剖析系列:下载队列类DownloadQueue
下载队列类DownloadQueue代表具有优先级的下载队列,该类的存储下载请求的数组链表专门按一定的优先级来存储下载请求的.该类的类图如下. 下载队列类DownloadQueue各个字段的含义说明如 ...
- 手写阻塞队列(Condition实现)
自己实现阻塞队列的话可以采用Object下的wait和notify方法,也可以使用Lock锁提供的Condition来实现,本文就是自己手撸的一个简单的阻塞队列,部分借鉴了JDK的源码.Ps:最近看面 ...
- Netty源码分析第7章(编码器和写数据)---->第3节: 写buffer队列
Netty源码分析七章: 编码器和写数据 第三节: 写buffer队列 之前的小节我们介绍过, writeAndFlush方法其实最终会调用write和flush方法 write方法最终会传递到hea ...
- PHP怎样写延时队列(定时器)
背景 PHP没有定时器,依托的都是crontab这样的系统工具,也没有go中defer这样的延时方法,本文介绍几种PHP写延时队列的几种姿势. 延时队列的定义 普通的队列是先进先出,但是延时队列并不是 ...
- 弹出窗口a标签写下载,再弹出窗口
如果这个窗口是弹出出口,直接<a href="">点击下载<a>是不行的,得用js这样写,弹出并关闭,不然会回到首页,如果没有定义首页会报错,<a h ...
- 三 基于Java数组手写循环队列
Code: package dataStucture2.stackandqueue; /** * 手写循环队列 * * @param <E> */ public class MyLoopQ ...
随机推荐
- 搭建jenkins
使用Jenkins配置Git+Maven的自动化构建 实现背景:Jenkins通过给定的代码地址URL,将代码拉取到其“宿主服务器”(就是Jenkins的安装位置),进行编译.打包和发布到容器中.在J ...
- Tornado简介
Tornado是一个具有强大异步功能的Python Web框架. Hello World 使用pip安装tornado: pip install tornado 编写控制器: import torna ...
- [BJOI 2018]求和
Description 题库链接 给你一棵 \(n\) 个结点的有根树, \(m\) 次询问这棵树上一段路径上所有节点深度的 \(k\) 次方和. \(1\leq n\leq 300000,1\leq ...
- webapi找到了与该请求匹配的多个操作
关于这个问题是路由在找方法的时候层没有指定对,同一个链接,同样的参数导致路由找不到方法导致的报错,可以在WebApiConfig中多配置一层,比如"api/{controller}/{act ...
- StreamRead和StreamWriter的使用
//StreamRead来读取一个文件 using (StreamReader sr = new StreamReader(@"C:\Users\enle\Desktop\新建文本文档.tx ...
- Jsp&Servlet入门级项目全程实录第2讲
惯例广告一发,对于初学真,真的很有用www.java1234.com,去试试吧! 1.导入jquery-easyui-1.3.3包( http://www.jeasyui.com/) 2.在页面导入e ...
- [javaSE] 单例设计模式
四人帮设计了23中设计模式 单例设计模式:解决一个类在内存中只存在一个对象 构造函数私有化 在类中创建一个本类对象 提供一个方法可以获取该对象 class Single{ private static ...
- Leetcode 计划
如何正确高效地使用LeetCode? LeetCode按照怎样的顺序来刷题比较好? LeetCode 题目总结/分类 Leetcode 简略题解 - 共567题 500. Keyboard Row [ ...
- redis 批量删除key
redis-cli -h -p keys -p del s
- win8.1 pro-64位下安装配置MinGW—64位
1.下载MinGW-w64位:http://mingw-w64.org/doku.php 点击Downloads 说明:这边使用的是在线安装方式: 在网站里可以看到他安装后的文件夹: 2.安装 运行m ...