Cache in Swift

Working with Data Locally

Tolga Taner
2 min readMar 15, 2022
Photo by Sigmund on Unsplash

Caching provides the apps more responsive and useful for example, when it is offline mode and prevents data loading over and over again. Thanks to caching, we can easily use app features as we want. In iOS, the device can delete smartly all caches when it is running on low memory. Let’s look at howNSCacheworks in iOS.

NSCache

NSCache needs two reference type objects that are one of them is key corresponding to value, other one is value.

Therefore, if we want to cache a value type object come from the webservice, we need to write a wrapper that contains a generic value type object variable inside a reference type object. NSCache doesn’t allow any value type object to cache so its type is decodable because we often want to show value type objects in a list.

Let’s create a new protocol named CacheProtocol to create, read, delete cache operation for our object. It has two generic types named AnyObject asInput and Outputas Decodable and create, read, delete functions respectively.

In our example,We want to cache worker and use it from cache until a certain day of the month. We decode worker object from the web service to write it to cache and read when our app is offline. To achieve that, since we can’t use value type anywhere, we need to change definition of id to create new reference type named UnwrappedKey inside Worker. It is inherited NSObject to checking uniqueness by calculating its hash value.

For using the whole implementation on Worker, we need a new manager named WorkerCacheManager to be conformed defined cache protocol. In WorkerCacheManager, associatedtypes come from the protocol are StructWrapper type and Decodable type. Because we give a reference type object to cache and get back casted value type object. To do that, first, we need to handle upcoming errors such as; type casting, caching failure operation. After that, we can easily cache changed reference type object from value type object and use it anywhere as value type object.

Even if NSCache does not support value type object caching, we found a workaround way to break this. We can use NSCache, if we do not want to call any web service each time and data is not be changed for a long time.

--

--