用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 ...
随机推荐
- mysql RC下不存在则插入
mysql版本:5.7 目的:在RC下,name列上仅有key索引,并发插入name时不出现重复数据 RC不加gap lock,并且复合select语句是不加锁的快照读,导致两个事务同时进行都可插入, ...
- koa2开发入门
一.koa2入门 1.创建koa2工程 首先,我们创建一个目录hello-koa并作为工程目录用VS Code打开.然后,我们创建app.js,输入以下代码: // 导入koa,和koa 1.x不同, ...
- jqGrid随窗口大小变化自适应大小-转
第一种: jqGrid随窗口大小变化自适应宽度 $(function(){ $(window).resize(function(){ $("#listId").setGridWid ...
- 使用Quartz.net来执行定时任务
Quartz.net使用方法:http://www.cnblogs.com/lizichao1991/p/5707604.html 最近,项目中需要执行一个计划任务,组长就让我了解一下Quartz.n ...
- json list数据递归生成树状层级JSON
<!DOCTYPE html> <html> <head> <script> var data=[ {"id":"aaa& ...
- Java线程池,你了解多少?
一.前言 随着业务的发展,单线程已经远远不能满足,随即就有多线程的出现.多线程虽然能解决单线程解决不了的事情,但是它也会给你带来额外的问题.比如成千上万甚至上百万的线程时候,你系统就会出现响应延迟.卡 ...
- Node.js数据流Stream之Duplex流和Transform流
Duplex流一个很好的例子是TCP套接字连接.需要实现_read(size)和_Write(data,encoding,callback)方法. var stream = require('stre ...
- unity简单动画实现
1:创建一个Sprite Render (player)的动画对象并添加脚本Player,点击主菜单“Window(视窗)→Animation(动画窗口)”Animation面板(选中需要动画的对象) ...
- WPF popup被截断的原因和修改方法
原因:wpf里 popup不能超过屏幕75%的面积,不知道为什么要这么设置? 修改方法: private void SetPopupScreen() { Rect rtWnd = , , gridMa ...
- 不用中间变量,交换a、b值
如果要交换a.b之间的值,一般的做法是: tmp=a;a=b;b=tmp;这种方法不得不使用一个临时变量. 从网上学来一个方法,可以不用使用临时变量: a^=b^=a^=b; 这样计算之后,就可以交换 ...