用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 ...
随机推荐
- (转)linux内核调优参数对比和解释
[net] ######################## cat /proc/sys/net/ipv4/tcp_syncookies # 默认值:1 # 作用:是否打开SYN Cookie功能,该 ...
- logstash-jdbc-input与mysql数据库同步
大多数情况下我们的数据都存放在了数据库中,但是elasticsearch它有自己的索引库,那么如果我们在做搜索的是时候就需要将数据库中的数据同步到elasticsearch中,在这里我们使用logst ...
- 《Head First 设计模式》读后总结:基础,原则,模式
基础 抽象 封装 多态 继承 原则 封装变化 多用组合,少用继承 针对接口编程,不针对实现编程 为交互对象之间的松耦合设计而努力 类应该对扩展开放,对修改关闭 依赖抽象,不要依赖具体类 只和朋友交谈 ...
- seajs源码分析(一)---整体结构以及module.js
1,seajs的主要内容在module.js内部,最开始包含这么几个东西 var cachedMods = seajs.cache = {} var anonymousMeta var fetchin ...
- Memcached理解笔2---XMemcached&Spring集成
一.Memcached Client简要介绍 Memcached Client目前有3种: Memcached Client for Java SpyMemcached XMemcached 这三种C ...
- Border属性的各种变化
本文前部分转自http://www.cnblogs.com/binyong/archive/2009/02/21/1395386.html,但是文章并未解释实现的原理,因此,后面本文也对次进行了解释. ...
- ELK 方案
转自:https://blog.csdn.net/enweitech/article/details/81744250 今天临时收到一个企业客户的项目需求,需要对所有WIndows业务服务器的日志进行 ...
- (译) 在AngularJS中使用的表单验证功能
验证功能是AngularJS里面最酷炫的功能之一,它可以让你写出一个具有良好用户体验的Web应用. 在AngularJS中,有许多用于验证的指令.我们将先学习几个最流行的内置指令,然后再创建一个自定义 ...
- sql server 运算
--Sql Server 乘法运算--select (d.RepaymentSchedule*d.MonthlyPayment) as ExpectedReceivablePayment from T ...
- emberjs 按年月分组
一个集合,里面有年和月的属性,按照年和月进行分组显示数据 + item.TopicMonth }).map(function (value, key) { return { time: { year: ...