/MemoryCache

MemoryCache is type-safe memory cache. Currently, NSCache wrapper

Primary LanguageSwiftMIT LicenseMIT

MemoryCache

CI Status Version License Platform

Overview

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)

Usage

Basic

Define keys

extension MemoryCache.KeyType {
    static let dog = MemoryCache.Key<Dog>(rawValue: "dog")
}

Set caches

MemoryCache.default.set(dog, for: .dog)

Load caches

let dog = try MemoryCache.default.load(for: .dog)

Remove caches

  • 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()

Others

Properties

/// 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

Implement delegate

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.
    }
}

Expiration date

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)

Requirements

  • Swift 4.2 ~
  • Xcode 10.1 ~

Installation

CocoaPods

MemoryCache is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod 'MemoryCache'

Carthage

You can integrate via Carthage, too. Add the following line to your Cartfile :

github "yysskk/MemoryCache"

and run carthage update

To do

  • expiration date of cache
  • LRU

Author

Yusuke Morishita

Support via PayPal

License

MemoryCache is available under the MIT license. See the LICENSE file for more info.