import UIKit /// 图片缓存管理单例,负责图片的缓存、读取和清除 class ImageCacheManager { static let shared = ImageCacheManager() private let cache = NSCache() // 私有初始化,确保单例 private init() { // 可设置缓存上限(可选) cache.totalCostLimit = 1024 * 1024 * 100 // 100MB } /// 从缓存获取图片 /// - Parameter url: 图片URL字符串 /// - Returns: 缓存的图片(如果存在) func getImage(for url: String) -> UIImage? { return cache.object(forKey: url as NSString) } /// 保存图片到缓存 /// - Parameters: /// - image: 要缓存的图片 /// - url: 图片URL字符串(作为缓存键) func saveImage(_ image: UIImage, for url: String) { cache.setObject(image, forKey: url as NSString) } /// 清除指定URL的图片缓存 /// - Parameter url: 图片URL字符串 func removeImage(for url: String) { cache.removeObject(forKey: url as NSString) } /// 清除所有图片缓存 func clearAllCache() { cache.removeAllObjects() } }