缓存

这是一个用 Swift 编写的适用于 iOS 和 macOS 的简单磁盘和内存缓存。 它可以缓存 Codable 类型、NSCoding 类型、基本类型(StringIntArray 等)。

为什么要使用它?

以下是一些您可能希望使用此库进行缓存的原因

兼容性

用法

安装

Cocoapod

将以下行添加到您的 Podfile

pod 'DataCache'

注意:如果以上 pod 不起作用,请尝试在 Podfile 中使用以下 pod 定义
pod 'DataCache', :git => 'https://github.com/huynguyencong/DataCache.git'

Swift Package Manager

在 Xcode 中,选择菜单 File -> Swift Packages -> Add Package Dependency。 选择一个目标,然后将此链接添加到输入字段:https://github.com/huynguyencong/DataCache.git

手动

Sources 文件夹中的所有文件添加到您的项目。

简单易用

使用默认缓存或创建新缓存(如果需要)。 在每个缓存实例中,您可以设置缓存大小和过期时间。

读取和写入对象

缓存 Codable 类型,包括符合 Codable 协议的自定义类型,以及默认情况下已符合 Codable 的基本类型(StringInt 等)。

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)")
}

读取和写入 UIImageNSImage

// 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")

读取和写入 Data

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
}

创建自定义 Cache 实例

除了使用默认缓存 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