SwiftyCache 0.9.5

SwiftyCache 0.9.5

测试已测试
语言语言 SwiftSwift
许可 Apache 2
发布上次发布2016年4月
SPM支持 SPM

Ma Haoming 维护。



  • Ma Haoming

SwiftyCache

SwiftyCache 是一个基于日志的磁盘 LRU 缓存库,它使用 Swift 2.2 重新实现了 Java 库 DiskLruCache

DiskLruCache 简史

DiskLruCache 最初来自 Android 开源项目,并由 Jake Wharton 以及其他贡献者维护于 GitHub。Square 已将其修改版集成到 OkHttp 中。由于 OkHttp 自 Android 4.4 起一直是 HttpUrlConnection 的内置 HTTP 客户端,因此现代 Android 设备都内置了 DiskLruCache 版本。

功能

以下描述来自 DiskLruCache,进行了相应修改。

SwiftyCache 是基于 LRU 策略在文件系统上使用固定空间的缓存。每个缓存条目都有一个字符串键和一定数量的值。每个键都必须匹配正则表达式 [a-z0-9_-]{1,120}。值是字节序列,可通过 NSData 对象或字符串访问。每个值的字节数必须在 0 到NSData对象最大容量之间。

缓存将数据存储在文件系统上的目录中。此目录必须是缓存独有的;缓存可能会从其目录中删除或覆盖文件。如果有多个进程同时使用同一缓存目录,则会发生错误。

此缓存限制了其在文件系统上存储的字节数。当存储的字节数超过限制时,缓存会自动在后台移除最近最少使用的条目,直到满足限制为止。此限制不是严格的:缓存可能在等待文件删除时暂时超出限制。此限制不包括文件系统开销或缓存日志,因此空间敏感的应用程序应设置保守的限制。

客户端调用 setData 创建或更新条目的值,或调用 setPartialData 更新现有条目的部分值。

  • 当使用setData创建或更新条目时,必须提供完整的一组值;如果需要,可以使用空值作为占位符。
  • 当使用setPartialData进行部分更新条目时,无需为每个值提供数据;值将默认使用其之前的值。

客户端调用getSnapshotForKey以读取条目的快照。读取将在后台派发队列中执行读取操作时的值进行观察。操作后的更新和删除不会影响快照中的值。

使用方法

let cachesDirURL = NSFileManager.defaultManager().URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask)[0]
let cacheDir = cachesDirURL.URLByAppendingPathComponent("TestCache", isDirectory: true).path!

let valueCount = 2 // each entry has two fields

let diskCache = DiskLRUCache(cacheDir: cacheDir, cacheVersion: 1, valueCount: valueCount, maxSize: 1024*1024*2)

let value0 = "Hello, world!".dataUsingEncoding(NSUTF8StringEncoding)!
let value1 = "Hello, SwiftyCache!".dataUsingEncoding(NSUTF16StringEncoding)!

let key = "Hello"
diskCache.setData([value0, value1], forKey: key)
diskCache.getSnapshotForKey(key) { (error: NSError?, snapshot: CacheEntrySnapshot?) in
    if let snapshot = snapshot {
        NSLog(snapshot.getStringDataAtIndex(0, encoding: NSUTF8StringEncoding)!)
        NSLog(snapshot.getStringDataAtIndex(1, encoding: NSUTF16StringEncoding)!)
    }
}

安装

许可

Copyright 2016 SwiftyCache

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   https://apache.ac.cn/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.