MemoryCache - type-safe, thread-safe memory cache class in Swift

Overview

MemoryCache

CI Status codecov Version License Platform

Overview

MemoryCache is a memory cache class in swift.

  • The MemoryCache class incorporates LRU policies, which ensure that a cache doesn’t use too much of the system’s memory. If memory is needed by other applications, it removes some items from the cache, minimizing its memory footprint.
  • You can add, remove, and query items with expiration in the cache from different threads without having to lock the cache yourself. ( thread-safe )
  • Unlike the NSCache class, the cache guarantees a type by its key. ( type-safe )
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)

Usage

Basic

Defining keys

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

Adding a Cached Value

memoryCache.set(dog, for: dogKey)

Getting a Cached Value

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

Removing Cached Values

  • Removes the cache of the specified key.
memoryCache.remove(for: dogKey)
  • Removes the cache of the specified key if it expired.
memoryCache.removeIfExpired(for: dogKey)
  • Removes All.
memoryCache.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

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

Implement delegate

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

Expiration date

You can specify expiration date for cache. The default expiration is .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)

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

Author

Yusuke Morishita

Support via PayPal

License

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

You might also like...
A simple cache that can hold anything, including Swift items

CacheIsKing CacheIsKing is a simple cache that allows you to store any item, including objects, pure Swift structs, enums (with associated values), et

SwiftyCache is a dynamic and auto-managed cache written in Swift
SwiftyCache is a dynamic and auto-managed cache written in Swift

SwiftyCache is a dynamic and auto-managed cache written in Swift. Unlike a simple cache system, it allows you to keep some data even in different executions. Guaranteeing persistence, when desired, without increasing the time required to save or recover data.

High performance cache framework for iOS.
High performance cache framework for iOS.

YYCache High performance cache framework for iOS. (It's a component of YYKit) Performance You may download and compile the latest version of sqlite an

Everyone tries to implement a cache at some point in their iOS app’s lifecycle, and this is ours.
Everyone tries to implement a cache at some point in their iOS app’s lifecycle, and this is ours.

Everyone tries to implement a cache at some point in their app’s lifecycle, and this is ours. This is a library that allows people to cache NSData wit

UITableView cell cache that cures scroll-lags on cell instantiating

UITableView + Cache https://github.com/Kilograpp/UITableView-Cache UITableView cell cache that cures scroll-lags on a cell instantiating. Introduction

Fast, non-deadlocking parallel object cache for iOS, tvOS and OS X

PINCache Fast, non-deadlocking parallel object cache for iOS and OS X. PINCache is a fork of TMCache re-architected to fix issues with deadlocking cau

Cache library for videos for React Native

@lowkey/react-native-cache Cache everything Installation npm install @lowkey/react-native-cache Usage import ReactNativeCache from "@lowkey/react-nati

CachedAsyncImage is the simplest way to add cache to your AsyncImage.

CachedAsyncImage 🗃️ CachedAsyncImage is AsyncImage, but with cache capabilities. Usage CachedAsyncImage has the exact same API and behavior as AsyncI

🏈 Cache CocoaPods for faster rebuild and indexing Xcode project.
🏈 Cache CocoaPods for faster rebuild and indexing Xcode project.

Motivation Working on a project with a huge amount of pods I had some troubles: - Slow and unnecessary indexing of pods targets, which implementation

Comments
  • Dependabot couldn't find a <anything>.yml for this project

    Dependabot couldn't find a .yml for this project

    Dependabot couldn't find a .yml for this project.

    Dependabot requires a .yml to evaluate your project's current Github_actions dependencies. It had expected to find one at the path: /.github/workflows/<anything>.yml.

    If this isn't a Github_actions project, or if it is a library, you may wish to disable updates for it from within Dependabot.

    You can mention @dependabot in the comments below to contact the Dependabot team.

    opened by dependabot-preview[bot] 0
  • Support cache expiration

    Support cache expiration

    Example codes

     /// 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)
    
    opened by yysskk 0
  • Upgrade to GitHub-native Dependabot

    Upgrade to GitHub-native Dependabot

    Dependabot Preview will be shut down on August 3rd, 2021. In order to keep getting Dependabot updates, please merge this PR and migrate to GitHub-native Dependabot before then.

    Dependabot has been fully integrated into GitHub, so you no longer have to install and manage a separate app. This pull request migrates your configuration from Dependabot.com to a config file, using the new syntax. When merged, we'll swap out dependabot-preview (me) for a new dependabot app, and you'll be all set!

    With this change, you'll now use the Dependabot page in GitHub, rather than the Dependabot dashboard, to monitor your version updates, and you'll configure Dependabot through the new config file rather than a UI.

    If you've got any questions or feedback for us, please let us know by creating an issue in the dependabot/dependabot-core repository.

    Learn more about migrating to GitHub-native Dependabot

    Please note that regular @dependabot commands do not work on this pull request.

    dependencies 
    opened by dependabot-preview[bot] 1
Owner
Yusuke Morishita
Software Engineer
Yusuke Morishita
💾 Simple memory & disk cache

Cache ?? Simple memory & disk cache Usage ??‍?? Default let cache = Cache<String>() try memory.save("MyValue", forKey: "MyKey") let cached = try cac

SeongHo Hong 2 Feb 28, 2022
Awesome Cache Delightful on-disk cache (written in Swift). Backed by NSCache for maximum performance

Awesome Cache Delightful on-disk cache (written in Swift). Backed by NSCache for maximum performance and support for expiry of single objects. Usage d

Alexander Schuch 1.3k Dec 29, 2022
Cache - Nothing but Cache.

Cache doesn't claim to be unique in this area, but it's not another monster library that gives you a god's power. It does nothing but caching, but it does it well. It offers a good public API with out-of-box implementations and great customization possibilities. Cache utilizes Codable in Swift 4 to perform serialization.

HyperRedink 2.7k Dec 28, 2022
Apple Asset Cache (Content Cache) Tools

AssetCacheTool A library and tool for interacting with both the local and remote asset caches. This is based on research I did a few years ago on the

Kenneth Endfinger 21 Jan 5, 2023
Thread -safe access to a lazily retrieved value, with optional validity checking

SerialUpdatingValue Thread-safe access to a lazily retrieved value, with optional validity checking Motivation Swift's Structured Concurrency provides

Smiley Rob 3 Nov 11, 2022
A type-safe swifty wrapper around NSCache.

swift-cache A type-safe swifty wrapper around NSCache. Getting Started Add swift-cache as a dependency to your project using SPM. .package(url: "https

Binary Scraping 2 Jun 3, 2022
CachyKit - A Caching Library is written in Swift that can cache JSON, Image, Zip or AnyObject with expiry date/TTYL and force refresh.

Nice threadsafe expirable cache management that can cache any object. Supports fetching from server, single object expire date, UIImageView loading etc.

Sadman Samee 122 Dec 28, 2022
Cachyr A typesafe key-value data cache for iOS, macOS, tvOS and watchOS written in Swift.

Cachyr A typesafe key-value data cache for iOS, macOS, tvOS and watchOS written in Swift. There already exists plenty of cache solutions, so why creat

Norsk rikskringkasting (NRK) 124 Nov 24, 2022
Carlos - A simple but flexible cache, written in Swift for iOS 13+ and WatchOS 6 apps.

Carlos A simple but flexible cache, written in Swift for iOS 13+ and WatchOS 6 apps. Breaking Changes Carlos 1.0.0 has been migrated from PiedPiper de

National Media & Tech 628 Dec 3, 2022
A lightweight generic cache for iOS written in Swift with extra love for images.

Haneke is a lightweight generic cache for iOS and tvOS written in Swift 4. It's designed to be super-simple to use. Here's how you would initalize a J

Haneke 5.2k Dec 29, 2022