Disk Cache: What It Is, iOS Disk Cache and Operating Principles

Author: IT Sectr Published: 2026-07-11 Reading time: 7 min

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 — storing data on disk to speed up repeated access and reduce traffic
  • URLCache — built-in HTTP request caching mechanism in iOS
  • Caches directory — a dedicated Sandbox directory for temporary app data
  • Cache invalidation is critical for data freshness — time-based, event-based, and version-based strategies
  • The system may clear the cache when disk space is low — cache must not contain irreplaceable data

What Is Disk Cache in iOS?

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: Built-in Caching Mechanism

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.

swift
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 Strategies and Invalidation

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.

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

Cache Performance and Limitations

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 TypeTypical Hit RatioRecommended Cache Size
Images70–90%100–500 MB
API JSON responses40–60%10–50 MB
Video/Audio30–50%500 MB — 1 GB
Fonts and resources90–99%5–20 MB
Web content50–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.

Best Practices for Caching in iOS

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

What Is Disk Cache in iOS?

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.

How Is Disk Cache Different from RAM Cache?

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.

Can iOS Delete My Cache?

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.

How to Choose the Right Cache Size?

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.

How to Clear Cache in an iOS App?

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

  • Disk Cache — temporary data storage on disk for faster repeated access and reduced traffic
  • URLCache — built-in Foundation HTTP request caching with Cache-Control support
  • Caches directory — Sandbox directory for temporary data, cleared by the system when space is low
  • Invalidation is performed by TTL, event, version, or LRU — choice depends on data type
  • Hit ratio — key cache efficiency metric: 70%+ for images, 40–60% for API
  • Two-level cache (RAM + Disk) — standard architecture for iOS apps
  • Security — sensitive data must not be cached to disk without encryption

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.

Discuss the project

Read also