Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import Foundation
public class QuotesCache: NSObject
{
/// Nuestra cache
private let cache: NSCache<NSString, NSData>
/// Recuperamos un objeto de la cache
public subscript(key: String) -> Data?
{
let theKey = key as NSString
return self.cache.object(forKey: theKey) as Data?
}
/**
Creamos la cache y asignamos un delegado
*/
override public init()
{
self.cache = NSCache()
super.init()
self.cache.delegate = self
}
/**
Añade una cita a la caché.
El usuario nos pasa un `Data` como valor un `String`
con el nombre del recurso que representa la cita.
Los convertimos en un NSData y NSString respectivamente
para operar con nuestra caché.
- Parameters:
- quote: Los bytes que representan la cita
- key: La clave por la que buscamos la imagen
*/
public func add(_ quote: Data, forKey key: String) -> Void
{
let theData = quote as NSData
let theKey = key as NSString
self.cache.setObject(theData, forKey: theKey)
}
/**
Elimina una entrada
*/
public func removeItem(forKey key: String) -> Void
{
let theKey = key as NSString
self.cache.removeObject(forKey: theKey)
}
}
//
// MARK: - NSCacheDelegate Protocol -
//
extension QuotesCache: NSCacheDelegate
{
/**
Nos avisa cuando un objeto va a ser eliminado de la cache
*/
public func cache(_ cache: NSCache<AnyObject, AnyObject>, willEvictObject obj: Any) -> Void
{
...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.