Skip to content

Instantly share code, notes, and snippets.

@fitomad
Created May 28, 2019 14:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fitomad/e04306085553c59babfcd99e3de01925 to your computer and use it in GitHub Desktop.
Save fitomad/e04306085553c59babfcd99e3de01925 to your computer and use it in GitHub Desktop.
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