Disk Cache is a mechanism for temporarily storing data on a device’s disk, allowing iOS applications to speed up repeated access to previously loaded resources. According to Apple Developer Documentation, 2024, Disk Cache reduces network usage, decreases battery load, and enables offline app operation. iOS provides several built-in caching mechanisms: URLCache for network requests, NSCache for RAM, and custom implementations through the Caches directory.
Key Takeaways
Disk Cache is a technology for temporarily storing data on a device’s permanent storage (flash memory) to speed up subsequent requests for the same data. Unlike RAM cache, Disk Cache persists data after app and even device restarts.
iOS provides two main caching levels: volatile (NSCache, memory) and disk-based (URLCache, file system). Disk cache is 10–100 times slower than volatile cache but significantly faster than a network request — the difference can be 2 to 3 orders of magnitude. The optimal strategy uses a two-level cache: memory for hot data and disk for cold data.
According to Apple Performance Optimization Guide, 2023, a properly configured Disk Cache reduces content loading time by 60–80% for repeat views and decreases traffic consumption by 40–70%. For media-rich applications (images, video, audio), caching is a critical UX factor.
URLCache is a built-in Foundation class that implements a combined cache for URLSession requests. It automatically saves server responses to disk and memory, managing cache size and invalidation policies based on HTTP headers such as Cache-Control, Expires, and ETag.
import Foundation
let cache = URLCache(
memoryCapacity: 50 * 1024 * 1024,
diskCapacity: 200 * 1024 * 1024,
diskPath: "network-cache"
)
URLCache.shared = cache
let config = URLSessionConfiguration.default
config.urlCache = cache
config.requestCachePolicy = .returnCacheDataElseLoad
let session = URLSession(configuration: config)
URLCache caching policies determine when to use cached data and when to perform a new request. The main policies include: useProtocolCachePolicy (based on server headers), reloadIgnoringLocalCacheData (always from server), returnCacheDataElseLoad (cache first), returnCacheDataDontLoad (cache only — offline mode).
Cache-Control is an HTTP header sent by the server with the response, specifying max-age (lifetime in seconds), must-revalidate (check freshness), no-cache (do not use without verification), and no-store (do not cache). iOS strictly respects these headers automatically when using URLCache with the useProtocolCachePolicy.
Custom caching is necessary when the built-in URLCache is insufficient — for storing processed images, serialized data models, or computation results. In such cases, developers build their own caching system based on the Caches directory in the app’s Sandbox.
class DiskCache<T: Codable> {
private let cacheDir: URL
private let encoder = JSONEncoder()
private let decoder = JSONDecoder()
init() {
let paths = FileManager.default
.urls(for: .cachesDirectory,
in: .userDomainMask)
cacheDir = paths[0].appendingPathComponent(
"data-cache", isDirectory: true
)
try? FileManager.default
.createDirectory(at: cacheDir,
withIntermediateDirectories: true)
}
func set(value: T, for key: String) {
let url = cacheDir.appendingPathComponent(
SHA256.hash(key)
)
if let data = try? encoder.encode(value) {
try? data.write(to: url)
}
}
func get(for key: String) -> T? {
let url = cacheDir.appendingPathComponent(
SHA256.hash(key)
)
guard let data = try? Data(contentsOf: url) else { return nil }
return try? decoder.decode(T.self, from: data)
}
func clearAll() {
try? FileManager.default
.removeItem(at: cacheDir)
}
}
Cache invalidation strategies determine when stored data is considered outdated: TTL (Time-To-Live) — data lives a fixed time after writing; event-driven — invalidation based on an event (e.g., data update on the server); version-based — invalidation when the API version or data format changes; LRU (Least Recently Used) — automatic removal of least used entries when the size limit is exceeded.
Practical rule: TTL is suitable for news and content that becomes outdated predictably. Event-driven is for server-managed data via push notifications. Version-based is for configurations and data model caches. LRU is a universal choice for media files with limited disk space.
Disk Cache performance is measured by hit ratio — the percentage of requests satisfied from the cache without a network call. A typical hit ratio for a well-configured image cache is 70–90%, for API responses — 40–60%, for streaming video — 30–50%.
| Data Type | Typical Hit Ratio | Recommended Cache Size |
|---|---|---|
| Images | 70–90% | 100–500 MB |
| API JSON responses | 40–60% | 10–50 MB |
| Video/Audio | 30–50% | 500 MB — 1 GB |
| Fonts and resources | 90–99% | 5–20 MB |
| Web content | 50–70% | 50–200 MB |
Disk Cache limitations in iOS: the system may delete the contents of the Caches directory at any time when disk space is low. This behavior is not configurable — iOS decides when and which cached files to delete. Therefore, the cache must not contain data that cannot be retrieved from the network or other sources.
Impact on flash memory: frequent writing to Disk Cache accelerates flash storage wear. iOS uses TRIM and wear leveling to minimize wear, but developers are advised to avoid excessive writes: do not update the cache more often than once every 5 minutes for the same file; batch small writes together; use NSCache for temporary data that does not need to be persisted to disk.
Two-level cache is the standard architecture for iOS apps: memory (NSCache) for frequently accessed data, and disk (URLCache or custom) for data that should persist between sessions. Lifetime in memory — minutes, on disk — hours or days.
Image caching: use specialized libraries (Kingfisher, SDWebImage, Nuke) that implement a two-level cache with automatic invalidation, memory handling, and asynchronous disk writing. Implementing a custom image cache requires consideration of decoding, color space, and scaling.
Cache and security: do not cache sensitive data (passwords, tokens, personal data) to disk without encryption. URLCache does not encrypt data by default — use NSFileProtection or application-level encryption for sensitive content. For authorized network requests, use the .reloadIgnoringLocalCacheData policy.
Cache monitoring: track hit ratio, current cache size, and writes per minute. If the hit ratio drops below 30%, the cache is inefficient and needs strategy revision or size increase. According to Point-Free (2024), cache monitoring is one of the most underestimated iOS app performance optimization practices.
Frequently Asked Questions
Disk Cache is a technology for storing data on a device’s disk to speed up repeated access. iOS’s built-in URLCache caches HTTP responses, and developers can create custom caches through the Caches directory.
RAM Cache (NSCache) stores data in RAM — faster, but lost on app restart. Disk Cache is slower but persists between sessions. The optimal strategy uses both levels: memory for hot data, disk for cold data.
Yes, the system may delete the contents of the Caches directory at any time when disk space is low. Therefore, never store irrecoverable data in the cache. Use the Documents directory for user documents.
Cache size depends on the data type: 100–500 MB for images, 10–50 MB for API responses, up to 1 GB for video. Monitor the hit ratio — if it drops below 50%, increase the cache size or change the invalidation strategy.
URLCache.removeAllCachedResponses() clears the built-in cache. For custom cache, delete files from the Caches directory via FileManager. Always provide users with an option to clear the cache through app settings.
Summary
We will develop a mobile application turnkey
IT Sectr creates iOS and Android applications for startups and businesses since 2017. We will advise you and propose the best solution.
Read also