当前位置:网站首页>iOS 缓存 -- NSCache和沙盒缓存
iOS 缓存 -- NSCache和沙盒缓存
2022-06-09 22:36:00 【JH_Cao】
1. 效果图

2.代码
import UIKit
class testView2: UIViewController {
let cache = NSCache<AnyObject, AnyObject>()
var imgeView = UIImageView()
let imgUrl = "https://t7.baidu.com/it/u=4162611394,4275913936&fm=193&f=GIF"
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
cache.countLimit = 10
//cache.totalCostLimit = 1024
cache.delegate = self
setUI()
}
func setUI() {
imgeView.frame = CGRect(x: 20, y: 100, width: UIScreen.main.bounds.size.width - 40, height: 350)
view.addSubview(imgeView)
let strArr = ["从网络读取数据","从内存缓存读取数据NSCache","删除ImageV","删除内存缓存NSCache","写入磁盘沙盒缓存","读取沙盒,并写入NSCache"]
for i in 0..<6 {
let btn = UIButton(frame: CGRect(x: 20, y: CGFloat(500 + i * 55), width: UIScreen.main.bounds.size.width - 40, height: 50))
btn.layer.cornerRadius = 10
btn.clipsToBounds = true
btn.setTitle(strArr[i], for: .normal)
btn.backgroundColor = UIColor(red: CGFloat(arc4random() % 255) / 255.0, green: CGFloat(arc4random() % 255) / 255.0, blue: CGFloat(arc4random() % 255) / 255.0, alpha: 1)
btn.tag = i
btn.addTarget(self, action: #selector(clickBtn(_:)), for: .touchUpInside)
view.addSubview(btn)
}
}
}
@objc
extension testView2 {
func clickBtn(_ sender: UIButton) {
switch sender.tag {
case 0:
print("从网络读取数据")
btn1()
case 1:
print("从内存缓存读取数据NSCache")
btn2()
case 2:
print("删除ImageV")
btn3()
case 3:
print("删除内存缓存NSCache")
btn4()
case 4:
print("写入磁盘沙盒缓存")
btn5()
case 5:
print("读取沙盒,并写入NSCache")
btn6()
default:
break
}
}
func btn1() {
let session = URLSession.shared
let url = NSURL(string: imgUrl)
let downloadTask = session.dataTask(with: url! as URL) { [unowned self](data, res, error) in
if error != nil {
print("error:\(String(describing: error))")
return
}
guard let imgData = data else {
print("没获取到图片数据")
return
}
self.cache.setObject(data as AnyObject, forKey: self.imgUrl as AnyObject)
let diskPath = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).map(\.path).last
let fileName = imgUrl.replacingOccurrences(of: "/", with: "")
let fullpath = URL(fileURLWithPath: diskPath ?? "").appendingPathComponent(fileName).path
let isSuccess = NSData(data: imgData).write(toFile: fullpath, atomically: true)
if isSuccess {
print("写入磁盘沙盒成功")
}
DispatchQueue.main.async {
imgeView.image = UIImage(data: imgData)
}
}
downloadTask.resume()
}
func btn2() {
DispatchQueue.global(qos: .background).async {[unowned self] in
let data = cache.object(forKey: imgUrl as AnyObject)
if data != nil {
DispatchQueue.main.async {
imgeView.image = UIImage(data: data as! Data)
}
} else {
print("内存缓存中无数据")
}
}
}
func btn3() {
imgeView.image = nil
}
func btn4() {
cache.removeAllObjects()
}
func btn5() {
// 下载的时候已经存
}
func btn6() {
let diskPath = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).map(\.path).last
let fileName = imgUrl.replacingOccurrences(of: "/", with: "")
let fullPath = URL(fileURLWithPath: diskPath ?? "").appendingPathComponent(fileName).path
print("diskPath:\(diskPath) \n fileName:\(fileName) \n fullPath:\(fullPath)")
guard let imageData = NSData(contentsOfFile: fullPath) else {
return
}
let imgData = imageData as Data
imgeView.image = UIImage(data: imgData)
cache.setObject(imgData as AnyObject, forKey: imgUrl as AnyObject)
}
}
// NSCache
extension testView2: NSCacheDelegate {
func cache(_ cache: NSCache<AnyObject, AnyObject>, willEvictObject obj: Any) {
print("清除缓存",obj)
}
}
边栏推荐
猜你喜欢

Ngnix 动态读取环境变量实现
![[volume guide] mendeley document management tool tutorial](/img/21/06649cfcf4d1c42f5c12dc372b519d.png)
[volume guide] mendeley document management tool tutorial

Leetcode(力扣)超高频题讲解(二)

Centos+mysql message: can't connect to local MySQL server through socket '/var/lib/mysql/mysql socket

I haven't seen this knowledge -- MySQL service evolution

How to protect personal rights and interests when the universe is not an illegal place?

Repeated web1 history in Web3

“35岁还没副业,都不好意思混职场”:摆脱死工资推荐这种副业

Exness: twitter said that it would continue to share data with musk and conduct shareholder voting at the end of July or early August

How to use sqlplus to remotely connect ASM instances
随机推荐
什么是分布式软件系统
基于JSP实现网上招聘系统
Is it safe for Huatai Securities to open an account
Two tower model: Ernie gram pre training and fine-tuning matching
Implementing Lmax disruptor queue from scratch (II) analysis of consumption dependency principle among multiple consumers and consumer groups
im即时通讯开发:离线消息、历史消息的实践
Sparksql source code series | resolvereferences rule count (*) details
How to protect personal rights and interests when the universe is not an illegal place?
Explanation of leetcode UHF questions (II)
uni-app是如何构建小程序的?
jg-文件上传代码-以及导出excel
又一重磅內容|海外現金貸產品形態及風控措施
Getting to know websocket
"At the age of 35, I have no sideline, so I'm embarrassed to mix in the workplace": get rid of the sideline of dead salary recommendation
Use of packet capturing tool fiddler
QNX system learning
Swift GCD Notify after concurrent execution Lock barrier
Im instant messaging development: Practice of offline messages and historical messages
这家估值25亿的公司,破产了?
JS 用正则表达式,验证密码包含数字和字母的方法