我有一个缓存的NSDictionary
。我需要实现一个带有时间戳的基于时间的setObject。 NSCache Class
没有setExpiry。任何帮助,将不胜感激。
这是我到目前为止的扩展名:
import Foundation
extension NSCache {
class var sharedInstance : NSCache {
struct Static {
static let instance : NSCache = NSCache()
}
return Static.instance
}
}
我在http://nshipster.com/nscache/中找到了
NSCache Extension
。有没有简单的时间戳到期方式实现?extension NSCache {
subscript(key: AnyObject) -> AnyObject? {
get {
return objectForKey(key)
}
set {
if let value: AnyObject = newValue {
setObject(value, forKey: key)
} else {
removeObjectForKey(key)
}
}
}
}
最佳答案
您还可以使用计时器清空队列:
private let ExpiringCacheObjectKey = "..."
private let ExpiringCacheDefaultTimeout: NSTimeInterval = 60
class ExpiringCache : NSCache {
/// Add item to queue and manually set timeout
///
/// - parameter obj: Object to be saved
/// - parameter key: Key of object to be saved
/// - parameter timeout: In how many seconds should the item be removed
func setObject(obj: AnyObject, forKey key: AnyObject, timeout: NSTimeInterval) {
super.setObject(obj, forKey: key)
NSTimer.scheduledTimerWithTimeInterval(timeout, target: self, selector: "timerExpires:", userInfo: [ExpiringCacheObjectKey : key], repeats: false)
}
// Override default `setObject` to use some default timeout interval
override func setObject(obj: AnyObject, forKey key: AnyObject) {
setObject(obj, forKey: key, timeout: ExpiringCacheDefaultTimeout)
}
// method to remove item from cache
func timerExpires(timer: NSTimer) {
removeObjectForKey(timer.userInfo![ExpiringCacheObjectKey] as! String)
}
}