MemoryCache is type-safe memory cache. It can benefit from NSCache
features by wrapping NSCache
.
let memoryCache = MemoryCache(name: "dog")
// Set dog in memoryCache.
memoryCache.set(dog, for: .dog)
// Load dog in memoryCache.
let cachedDog = try memoryCache.load(for: .dog)
// Remove dog in memoryCache.
memoryCache.remove(for: .dog)
extension MemoryCache.KeyType {
static let dog = MemoryCache.Key<Dog>(rawValue: "dog")
}
MemoryCache.default.set(dog, for: .dog)
let dog = try MemoryCache.default.load(for: .dog)
- Removes the cache of the specified key.
MemoryCache.default.remove(for: .dog)
- Removes the cache of the specified key if it expired.
MemoryCache.default.removeIfExpired(for: .dog)
- Removes All.
MemoryCache.default.removeAll()
/// The maximum total cost that the memoryCache can hold before it starts evicting caches.
var totalCostLimit: Int
/// The maximum number of caches the memoryCache should hold.
var countLimit: Int
/// Whether the cache will automatically evict discardable-content caches whose content has been discarded.
var evictsCachesWithDiscardedContent: Bool
import MemoryCache
class SomeClass: NSObject, MemoryCacheDelegate {
init() {
...
super.init()
MemoryCache.default.delegate = self
}
func memoryCache(_ memoryCache: MemoryCache, willEvict cache: Any) {
// Called when an cache is about to be evicted or removed from the memoryCache.
}
}
You can specify expiration date for cache. The default expiration is .never
.
/// The expiration date is `.never`.
memoryCache.set(dog, for: .dog, expiration: .never)
/// The expiration date is `.seconds("""10s""")`.
memoryCache.set(dog, for: .dog, expiration: .seconds(10))
/// The expiration date is `.date("""TOMORROW""")`.
memoryCache.set(dog, for: .dog, expiration: .date(Date().addingTimeInterval(60 * 60 * 24)))
/// Remove the cache of the specified key if it expired.
memoryCache.removeIfExpired(for: .dog)
- Swift 4.2 ~
- Xcode 10.1 ~
MemoryCache is available through CocoaPods. To install it, simply add the following line to your Podfile:
pod 'MemoryCache'
You can integrate via Carthage, too.
Add the following line to your Cartfile
:
github "yysskk/MemoryCache"
and run carthage update
- expiration date of cache
- LRU
MemoryCache
is available under the MIT license. See the LICENSE file for more info.