MemoryCache 1.1.0

MemoryCache 1.1.0

yysskk维护。



MemoryCache

CI Status codecov Version License Platform

概述

MemoryCache是一个Swift语言中的内存缓存类。

  • MemoryCache类内嵌LRU策略,确保缓存不会占用太多系统内存。当其他应用程序需要内存时,它会从缓存中移除一些项目,最小化其内存占用。
  • 您可以在不同的线程中添加、移除和查询具有<强烈>过期时间的缓存项,而无需自己锁定缓存。(线程安全
  • 与NSCache类不同,缓存通过其键保证一个类型。(类型安全
let memoryCache = MemoryCache.default // or initialize

// Defining a string (or hash) key for a dog value.
let dogKey = StringKey<Dog>("dog")

// Setting a dog value in memoryCache.
memoryCache.set(dog, for: dogKey)

// Getting a cached dog value in memoryCache.
let cachedDog = try? memoryCache.value(for: dogKey)

// Removing a cached dog value in memoryCache.
memoryCache.remove(for: dogKey)

使用

基本

定义键

let dogKey = StringKey<Dog>("dog")

添加缓存值

memoryCache.set(dog, for: dogKey)

获取缓存值

let dog = try? memoryCache.value(for: dogKey)

移除缓存值

  • 移除指定键的缓存。
memoryCache.remove(for: dogKey)
  • 如果已过期,则移除指定键的缓存。
memoryCache.removeIfExpired(for: dogKey)
  • 全部移除。
memoryCache.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

/// The total cost of values in the memoryCache.
var totalCost: Int

/// The number of values in the memoryCache.
var count: Int

/// A Boolean value indicating whether the memoryCache has no values.
var isEmpty: Bool

实现代理

import MemoryCache

class SomeClass: NSObject, MemoryCacheDelegate {

    let memoryCache: MemoryCache
    
    init() {
        memoryCache = MemoryCache.default
        
        ...
        
        super.init()

        memoryCache.delegate = self
    }
    
    func memoryCache(_ memoryCache: MemoryCache, willEvict cache: Any) {
        // Called when an cache is about to be evicted or removed from the memoryCache.
    }
}

过期日期

可以指定缓存的过期日期。默认过期为 .never

/// The expiration date is `.never`.
memoryCache.set(dog, for: dogKey, expiration: .never)

/// The expiration date is `.seconds("""10s""")`.
memoryCache.set(dog, for: dogKey, expiration: .seconds(10))

/// The expiration date is `.date("""TOMORROW""")`.
memoryCache.set(dog, for: dogKey, expiration: .date(Date().addingTimeInterval(60 * 60 * 24)))

/// Remove the cache of the specified key if it expired.
memoryCache.removeIfExpired(for: dogKey)

需求

  • Swift 4.2 ~
  • Xcode 10.1 ~

安装

CocoaPods

MemoryCache可通过CocoaPods获取。要安装它,只需将以下行添加到您的Podfile中

pod 'MemoryCache'

Carthage

您也可以通过Carthage进行集成。将以下行添加到您的Cartfile中

github "yysskk/MemoryCache"

然后运行carthage update

作者

Yusuke Morishita

Support via PayPal

许可证

MemoryCache 可在 MIT 许可下使用。有关更多信息,请参阅 LICENSE 文件。