To NSCache
or not to NSCache
, what is the URLCache
Almost every mobile app now-a-days rely on networking, either for JSON, image or advertisement. It’s rare to find an app in the AppStore that doesn’t manage data. To make the app fast and responsive sometimes app developer uses caching mechanism. Though caching is not just about improving UX by making the interface fast and responsive, it’s about efficiently managing data that will be used frequently. Not to say, it will effectively strip down repetitive tasks.
There are a lot of great third-party caching libraries available. Haneke, PINCache, Cache, Awesome Cache are some of the popular third-parties out there. Even image libraries, like SDWebImage, Kingfisher or Nuke provides great caching feature.
But sometimes using a library might be an overkill. Sometimes you might need a customized caching system or maybe you don’t like or trust third parties at all.
Apple’s Foundation
framework provides two caching API out of the box. NSCache
and URLCache
. NSCache
is an in-memory mutable collection to temporarily store key-value pairs. It's just an NSMutableDictionary
with auto-eviction policies in order to free up space in memory as needed, as well as more thread-safety and explicit copying, NSCopying
protocol, confirmation.
Let’s implement a simple custom UIImageView class that loads an image asynchronously and cache the image using NSCache
so that it won't perform the next network call for the same image.
As NSCache
is an in-memory cache, it will use system's memory and will allocate a proportional size to the size of images, or data in generic term. Until other applications need memory and system forces this app to minimize its memory footprint by removing some of its cached objects. Though, NSCache
doesn't guarantee that the eviction process will be in orderly manner. Moreover, the cached objects won't be there in next run. The main advantages of NSCache
are performance and auto-purging feature for objects with transient data that are expensive to create.
For any network data management we should use URLCache
rather than NSCache
for caching any data. Because, URLCache
is both in-memory and on-disk cache, and it doesn't allocate a chunk of memory for it's data. You can define it's in-memory and on-disk size, which is more flexible. URLCache
will persist the cached data until the system runs low on disk space.
So, the revised implementation of previous UIAsyncImageView
class would be as,
And you can change the cache size and disk cache path in shared URLCache
.
I usually put this block of code in an extension file and call it from AppDelegate
's didFinishLaunchingWithOptions launchOptions:
method.
and in AppDelegate.swift
For more details, check NSCache
and URLCache
pages from Foundation
documentation.
That’s all for this tutorial. Let me know if you have any corrections or questions for me. Happy Coding!
Originally posted at https://github.com/