Junior — Middle
Kā patstāvīgi īstenot kešatmiņas mehānismu bez ārējo bibliotēku izmantošanas?
sobes.tech AI
Atbilde no AI
Lai īstenotu vienkāršu kešēšanas mehānismu iOS bez trešo pušu bibliotēkām, vari izmantot vārdnīcu (Dictionary) datu glabāšanai ar atslēgām un vērtībām, kā arī pievienot loģiku kešatmiņas derīguma laika pārvaldībai.
Piemērs Swift valodā:
class SimpleCache<Key: Hashable, Value> {
private var cache = [Key: (value: Value, expiry: Date?)]()
private let defaultExpiry: TimeInterval
init(defaultExpiry: TimeInterval = 300) { // noklusējuma 5 minūtes
self.defaultExpiry = defaultExpiry
}
func set(_ value: Value, for key: Key, expiry: TimeInterval? = nil) {
let expiryDate = expiry != nil ? Date().addingTimeInterval(expiry!) : Date().addingTimeInterval(defaultExpiry)
cache[key] = (value, expiryDate)
}
func get(_ key: Key) -> Value? {
guard let entry = cache[key] else { return nil }
if let expiry = entry.expiry, expiry < Date() {
cache.removeValue(forKey: key)
return nil
}
return entry.value
}
func remove(_ key: Key) {
cache.removeValue(forKey: key)
}
func clear() {
cache.removeAll()
}
}
Šī klase ļauj saglabāt objektus ar atslēgām, automātiski dzēst novecojušos datus un manuāli pārvaldīt kešatmiņu.