How to cache data in Swift using NSCache

Swift NSCache

Posted on 7 Apr 2023 . 2 min read


When we develop apps for iOS, we need to perform heavy tasks such as loading images from the network, loading files, etc. It’s a very time-consuming task, which affects the performance of the application. Therefore, we cache or store temporary data for them and reuse them appropriately.


Swift uses NSCache to store temporary data in memory. It is a mutable collection that uses key-value pairs to store temporary data.


It evicts objects associated with data when the system is low on memory. The data that is evicted from the memory has to be recreated again. We can add, remove, or query items in the cache.


Syntax



The NSCache class constructor takes two objects: key type and object type.

let cache = NSCache<NSURL, UIImage>()


We can optionally give the cache a name for later use. By default, the value is an empty string.

let cache = NSCache<NSURL, UIImage>()
cache.name = “fetch images”


Storing object


We can set the value to the specified key using the setObject function, which takes two parameters: the object to store and the key name.

let image = UIImage(named: “kitten.png”)!
cache.setObject(image, forKey: “banner”)


Removing cache object


The removeObject function, which takes the key name of the object to be removed as a parameter, can be used to remove an object from cache.

cache.removeObject(forKey: “banner”)


And to remove all objects and empty the cache, use the removeAllObjects function.

cache.removeAllObjects()


Getting object value


The object method returns the value associated with a given key. It gives the value associated with the key or returns nil if there is no value.

if let image = cache.object(forKey: “banner”) {
  print("Image is in the cache")
} else {
  print("Image is not in the cache")
}


Cache Size


We set the maximum number of objects using the countLimit property. If we set countLimit to 0, there is no object. If an object’s limit increases, then it should be evicted from memory instantly.

cache.countLimit = 20


How to set total cost


We can set the totalCostLimit of an object when it is added to the cache. It specifies an object, such as the bytes of an object. The default value is 0; there is no cost value. If an object’s total cost exceeds the limit, it will be automatically removed from memory.

cache.totalCostLimit = 20_000_000


The bottom line


It’s good practice to use cache to store temporary data, which is very expensive and time-consuming. It increases the performance of the app and the resources of the system.


Don’t hesitate to contact me if you have any questions or queries. Follow me on twitter @gurjitpt for any updates.

Thanks!


More articles:


Share this article



Written By

Generic placeholder image

Gurjit Singh

I’m Computer Science graduate and an iOS Engineer who writes about Swift and iOS development. Follow me for more updates:


Discover articles by topics

SwiftUI Class Struct Networking XCode NSCache Enum Optionals Property Observers Closures Guard Reviews StoreKit App Store Algorithms Testing Operators Protocol Extensions Weak Unowned SwiftData WWDC23 GCD API Admob SwiftLint Lottie Foreach Objective-C UIKit NavigationSplitView

Related Articles


String Concatenation in Swift: A Comprehensive Guide

In any programming language, working with strings is essential, and Swift is no different.Whether you are building iOS apps......

2024-10-17 . 3 min read     String Concatenation

Read More »

Integrating SwiftUI with UIKit Using UIHostingController

With the introduction of SwiftUI, Apple has provided developers with a modern way to build user interfaces across all Apple platforms....

2024-07-09 . 3 min read     UIHostingController

Read More »

Deep Dive into Autorelease Pools in Swift

In the realm of software development, memory management plays a crucial role in ensuring the efficient allocation and deallocation of memory...

2024-01-28 . 4 min read     Swift Autorelease

Read More »

Swift enum equatable: with or without associated values

Swift enums provide a powerful way to model a set of related values. Enums can be equipped with associated values, allowing them to represen...

2024-01-24 . 3 min read     Swift Enums

Read More »

How to create Date Picker in SwiftUI

Use a DatePicker when creating a view that enables users to choose both a calendar date and, if needed, a specific time.In SwiftUI, you can ...

2024-01-16 . 2 min read     SwiftUI DatePicker

Read More »

Getting started with Swiftlint to enforce Swift style

SwiftLint is a tool that ensures Swift code adheres to defined style guidelines. It automates code review by identifying and suggesting impr...

2023-12-29 . 4 min read     Swift SwiftLint

Read More »