1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- //
- // KMThumbnailCache.swift
- // PDF Reader Pro
- //
- // Created by lizhe on 2024/8/9.
- //
- class KMThumbnailCache: NSObject {
- static let shared = KMThumbnailCache()
-
- private let maxCacheSize = 50
- // 外层字典以文档路径为键,内层字典以缩略图 ID 为键
- private var thumbnails: [String: [String: NSImage]] = [:]
- private var order: [String: [String]] = [:] // 记录每个文档路径的插入顺序
- // 添加缩略图及其文档路径
- func addThumbnail(for path: String, id: String, image: NSImage) {
- // 确保每个路径都有自己的字典和顺序数组
- if thumbnails[path] == nil {
- thumbnails[path] = [:]
- order[path] = []
- }
-
- // 获取当前路径的字典和顺序数组
- var currentThumbnails = thumbnails[path]!
- var currentOrder = order[path]!
-
- // 检查并维持每个路径的最大缓存大小
- if currentThumbnails.count >= maxCacheSize {
- if let oldestID = currentOrder.first {
- currentThumbnails.removeValue(forKey: oldestID)
- currentOrder.removeFirst()
- }
- }
-
- // 添加新缩略图
- currentThumbnails[id] = image
- currentOrder.append(id)
-
- // 更新字典和顺序数组
- thumbnails[path] = currentThumbnails
- order[path] = currentOrder
- }
- // 根据路径和 ID 获取缩略图
- func thumbnail(for path: String, id: String) -> NSImage? {
- return thumbnails[path]?[id]
- }
- // 根据路径和 ID 移除缩略图
- func removeThumbnail(for path: String, id: String) {
- guard var currentThumbnails = thumbnails[path],
- var currentOrder = order[path] else {
- print("Path or ID not found")
- return
- }
-
- if let index = currentOrder.firstIndex(of: id) {
- currentThumbnails.removeValue(forKey: id)
- currentOrder.remove(at: index)
- } else {
- print("ID not found in the given path")
- }
-
- // 更新字典和顺序数组
- thumbnails[path] = currentThumbnails
- order[path] = currentOrder
- }
- // 清空缓存
- func clearCache(for path: String? = nil) {
- if let path = path {
- thumbnails[path]?.removeAll()
- order[path]?.removeAll()
- } else {
- thumbnails.removeAll()
- order.removeAll()
- }
- }
- }
|