//
// CacheImage.swift
// GATransitionAnimation
//
// Created by houjianan on 2017/3/27.
// Copyright © 2017年 houjianan. All rights reserved.
//
/*
-- API --
1、The NSCache class incorporates various auto-eviction policies, which ensure that a cache doesn’t use too much of the system’s memory. If memory is needed by other applications, these policies remove some items from the cache, minimizing its memory footprint.
2、You can add, remove, and query items in the cache from different threads without having to lock the cache yourself.
3、Unlike an NSMutableDictionary object, a cache does not copy the key objects that are put into it.
/ 线程安全 不用加锁 自动删除 减少内存占用 不需要实现NSCopying/
*/
import UIKit
class GA_ImageLoader {
static let instance : GA_ImageLoader = GA_ImageLoader()
class var sharedLoader : GA_ImageLoader {
return instance
}
// 使用NSCache
var cache = NSCache<AnyObject, AnyObject>()
func imageForUrl(urlString: String, completionHandler:@escaping (_ image: UIImage?, _ url: String) -> ()) {
// 异步获取图片
DispatchQueue.global().async {
// 从缓存中取
let data: Data? = self.cache.object(forKey: urlString as AnyObject) as? Data
// 缓存中存在直接去除并在主线程返回
if let goodData = data {
let image = UIImage(data: goodData as Data)
DispatchQueue.main.async {
completionHandler(image, urlString)
}
return
}
// 不存在去下载 使用 URLSession
let downloadTask: URLSessionDataTask = URLSession.shared.dataTask(with: URL(string: urlString)!, completionHandler: { (data, response, error) in
if (error != nil) {
completionHandler(nil, urlString)
return
}
// 获得图片并且保存 主线程返回
if data != nil {
let image = UIImage(data: data!)
self.cache.setObject(data as AnyObject, forKey: urlString as AnyObject)
DispatchQueue.main.async {
completionHandler(image, urlString)
}
return
}
})
downloadTask.resume()
}
}
}
iOS-swift-图片缓存NSCache使用
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 本小节将会介绍有关报头的一些处理方式,并尝试进行最原始的图片加载、缓存等功能处理。最后使用PINRemoteIma...
- 『导言』 iOS开发中,如何保证图片只被下载一次?如何缓存图片?内存缓存?磁盘缓存?到底如何区别?如何联系? 温馨...
- iOS程序为沙盒机制,APP只能访问自己目录下的文件,不能直接访问其他目录内容,每个APP默认都会创建以下目录结构...
- 一步一步入门机器学习之一:Python(x,y)下载,安装,使用入门 CSDN博客2014.5.14 暂无评论 引...