KMThumbnailCache.swift 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. //
  2. // KMThumbnailCache.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by lizhe on 2024/8/9.
  6. //
  7. class KMThumbnailCache: NSObject {
  8. static let shared = KMThumbnailCache()
  9. private let maxCacheSize = 50
  10. private var thumbnails: [Int: NSImage] = [:]
  11. private var order: [Int] = [] // 记录插入顺序的数组
  12. func addThumbnail(id: Int, image: NSImage) {
  13. if thumbnails.count >= maxCacheSize {
  14. if let oldestID = order.first {
  15. thumbnails.removeValue(forKey: oldestID)
  16. order.removeFirst()
  17. }
  18. }
  19. thumbnails[id] = image
  20. order.append(id)
  21. }
  22. func thumbnail(for id: Int) -> NSImage? {
  23. return thumbnails[id]
  24. }
  25. func removeThumbnail(for id: Int) {
  26. if let index = order.firstIndex(of: id) {
  27. thumbnails.removeValue(forKey: id)
  28. order.remove(at: index)
  29. } else {
  30. print("ID not found")
  31. }
  32. }
  33. func clearCache() {
  34. thumbnails.removeAll()
  35. order.removeAll()
  36. }
  37. }