这是一个为 Swift 编写的优美而轻量级的缓存。已经在 iOS 和 OS X 上进行了测试。我写了一个小时多,因为我找不到足够好的东西,我认为您也会喜欢它。
用 XCode 6.3.1 和 Swift 1.2 进行了测试。需要 SwiftyJSON,但也意味着它是我唯一知道的与 SwiftyJSON 和 Alamofire 兼容的缓存,而且非常可靠!
试试吧。
只需将 SwiftCache.swift
的内容复制并插入到您的 XCode 中,无需其他操作。
// The above will save it for 60 seconds before expiring the cache
var names = SwiftCache(name: "friendsNames", expiresIn: 60)
// Want to clear the cache? Run this.
// names.expireCache()
names.respond { (data : [String]) in
if names.isCached() {
println("Saved in cache: \(data)")
println("Expires from cache in \(names.secondsLeftInCache()) seconds")
} else {
println("Written to cache: \(data)")
}
}.request { in
// Save to cache (it'll accept any datatype)
// In this case, it's a String Array (which is denoted in Swift as [String])
names.saveToCache(["Mike", "Jon", "Aziz", "Tim", "Joe", "Syeef", "Hamer", "Li", "Gregor"])
}
// Let's remember where a user said they're from (setting expiresIn to -1 means forever)
var currentUserCity = SwiftCache(name: "currentUserCity", expiresIn: -1)
// Want to clear the cache? Run this.
// currentUserCity.expireCache()
names.respond { (currentCity : String) in
// This will always be ran, but may be from the cache or directly from the block in .request
println("Hi there stranger from the wonderful city of \(currentCity)")
}.request { in
// Here, if the cache is empty or expired, you can show a UIView to ask for their location
let aLocationTheUserSelected : String = "Manchester, United Kingdom"
names.saveToCache(aLocationTheUserSelected)
}
在 MIT 许可协议 下发布