-
-
Save fitomad/e04306085553c59babfcd99e3de01925 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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