这是一个用 Swift 编写的适用于 iOS 和 macOS 的简单磁盘和内存缓存。 它可以缓存 Codable
类型、NSCoding
类型、基本类型(String
、Int
、Array
等)。
以下是一些您可能希望使用此库进行缓存的原因
将以下行添加到您的 Podfile
pod 'DataCache'
注意:如果以上 pod 不起作用,请尝试在 Podfile 中使用以下 pod 定义
pod 'DataCache', :git => 'https://github.com/huynguyencong/DataCache.git'
在 Xcode 中,选择菜单 File -> Swift Packages -> Add Package Dependency。 选择一个目标,然后将此链接添加到输入字段:https://github.com/huynguyencong/DataCache.git
将 Sources
文件夹中的所有文件添加到您的项目。
使用默认缓存或创建新缓存(如果需要)。 在每个缓存实例中,您可以设置缓存大小和过期时间。
缓存 Codable
类型,包括符合 Codable
协议的自定义类型,以及默认情况下已符合 Codable
的基本类型(String
、Int
等)。
do {
try DataCache.instance.write(codable: myCodableObject, forKey: "myKey")
} catch {
print("Write error \(error.localizedDescription)")
}
do {
let object: MyCodableObject? = try DataCache.instance.readCodable(forKey: "myKey")
} catch {
print("Read error \(error.localizedDescription)")
}
// on iOS
let image = UIImage(named: "myImageName")
// on macOS
let image = NSImage(named: "myImageName")
// will be written in a same way
DataCache.instance.write(image: image!, forKey: "imageKey")
let image = DataCache.instance.readImage(forKey: "imageKey")
let data = ... // your data
DataCache.instance.write(data: data, forKey: "myKey")
let data = DataCache.instance.readData(forKey: "myKey")
您可以按键清除,也可以全部清除,使用以下方法之一
DataCache.instance.clean(byKey: "myKey")
DataCache.instance.cleanAll()
它也会在过期后清除缓存。 默认过期时间为 1 周。 如果要自定义过期时间,请按照以下说明创建自定义缓存。
只需使您的类型符合 Codable 即可。
struct User: Codable {
let name: String
let yearOld: Double
}
除了使用默认缓存 DataCache.instance
之外,您还可以创建自己的缓存实例,然后可以设置不同的过期时间、磁盘大小、磁盘路径。 name 参数指定磁盘缓存的路径名。
let cache = DataCache(name: "MyCustomCache")
cache.maxDiskCacheSize = 100*1024*1024 // 100 MB
cache.maxCachePeriodInSecond = 7*86400 // 1 week
此开源代码使用 Kingfisher 库中的一些代码片段。
DataCache 在 MIT 许可下发布。 有关详细信息,请参阅 LICENSE。 版权所有 © Nguyen Cong Huy