NSCache
Also known as: nscache ios, in memory cache swift, ios nscache
NSCache is a mutable, thread-safe in-memory key-value cache in Apple's Foundation framework that automatically evicts its objects when the system comes under memory pressure, making it the recommended store for transient data like decoded images and computed results.
- NSCache is thread-safe and lives entirely in RAM, never on disk.
- It auto-evicts objects under memory pressure, so cached entries can vanish without warning.
- countLimit and totalCostLimit are advisory hints, not strict ceilings.
How NSCache works
NSCache behaves like a dictionary for caching: you store objects with `setObject(_:forKey:)` and retrieve them with `object(forKey:)`. Unlike a plain `NSDictionary` or Swift `Dictionary`, it is thread-safe and ties into the system's memory management. When iOS signals memory pressure, NSCache can automatically purge entries to free RAM, so cached objects may disappear at any time.
Eviction is influenced by `countLimit` (max number of objects) and `totalCostLimit` (a developer-supplied cost budget passed via `setObject(_:forKey:cost:)`). These are advisory hints, not hard guarantees, the system decides when and how much to evict.
When to use it and why it matters for storage
NSCache is purely in-memory, so it never adds to the app's on-disk footprint. It is ideal for data that is expensive to recreate but cheap to discard, such as decoded `UIImage` thumbnails. Because it auto-evicts, it pairs well with responding to `applicationDidReceiveMemoryWarning` and the lifecycle hooks that ask apps to shed memory.
Developers who instead cache the same objects to disk (in NSCachesDirectory) trade RAM for storage growth, which is exactly the kind of reclaimable bloat that storage cleaners surface as app cache.