DataCache 1.7

DataCache 1.7

测试已测试
Lang语言 SwiftSwift
许可证 MIT
发布最后发布2022年12月
SPM支持SPM

Nguyen Cong Huy维护。



  • 作者:
  • Huy Nguyen Cong

缓存

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

为什么要使用它?

有以下几个原因可能会让你想使用这个缓存库

  • 最简单、最直接的方式来缓存,把数据存储在内存和磁盘上。
  • 快速响应时间。Instead of waiting for data loading from Internet, now you can load it from cache before updating it from remote resources.
  • Loading data from cache, just update from remote source when the cache expired, will save user's Internet data (especially mobile data) and help improve battery life.
  • 它将在磁盘和内存上存储数据。当你读取缓存时,它将首先尝试从内存中获取数据。这使得读取速度很快。当RAM满时,它将自动清除内存缓存,所以它不会使你的应用程序耗尽内存。

兼容性

  • iOS 9/macOS 10.11及更高版本(如果你想在iOS 7上使用,请手动添加文件)
  • Swift 5及更高版本(对于更早的Swift版本,请使用更早的DataCache版本)

使用方法

安装

Cocoapod

将以下行添加到 Podfile 中

pod 'DataCache'

注意:如果上面的 pod 无法工作,请在 Podfile 中尝试使用下面的 pod 定义
pod 'DataCache', :git => 'https://github.com/huynguyencong/DataCache.git'

Swift Package Manager

在 Xcode 中,选择菜单 文件 -> Swift 包 -> 添加包依赖。选择一个目标,然后向输入字段添加此链接: 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()

它也会在过期后清除缓存。默认过期天数为一周。如果您想自定义过期时间,请按照以下说明创建自定义缓存。

为缓存能力自定义类

只需让您的类型符合 Codable 协议即可。

struct User: Codable {
    let name: String
    let yearOld: Double
}

创建自定义缓存实例

除了使用默认缓存 DataCache.instance 之外,您还可以创建自己的缓存实例,然后您可以设置不同的过期时间、磁盘大小和磁盘路径。名称参数指定磁盘缓存的路径名称。

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