How to use NSCache
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.
Introduction
NSCache is an in-memory cache class for Apple platforms that automatically evicts objects under memory pressure. It is a strong choice for temporary objects such as decoded images or computed results. Compared with a plain dictionary, NSCache is better suited for memory-sensitive apps.
Core Behavior of NSCache
NSCache stores key and value pairs and can evict entries at any time. Your app should treat cached values as optional and recomputable. This behavior is ideal for performance optimization, not for persistent storage.
In Swift, keys are typically NSString when using generic NSCache types.
Configure Size Limits
You can bound cache growth with countLimit and totalCostLimit. This helps control memory usage for large values such as images.
For cost calculations, use an estimate that is consistent across your app.
Build a Thread-Safe Loader with NSCache
NSCache is thread-safe for basic operations, so it pairs well with asynchronous loading.
The loader pattern centralizes cache hits and misses and keeps call sites clean.
When to Use NSCache Versus Dictionary
Use NSCache for disposable performance data that can be rebuilt. Use a dictionary when you need strict retention and predictable eviction rules managed by your own code. In many apps, both are useful for different layers.
If cache misses are expensive, combine NSCache with disk caching for a two-level strategy.
Eviction Observation with NSCacheDelegate
When tuning cache limits, it is useful to observe evictions. NSCacheDelegate gives you a callback when objects are removed.
This insight helps verify whether limits are too strict or too loose.
Design a Stable Cache Key Strategy
Cache misses often come from inconsistent keys, not from eviction. Define a single key format for each cached type. For image caching, include parameters that change output such as width, scale, and style variant.
A predictable key strategy improves hit rates and avoids duplicate memory usage for equivalent values.
Use Cache Plus Source of Truth
Treat NSCache as a fast layer in front of persistent storage or network fetches. On cache miss, read from the source of truth and refill the cache. This layered pattern gives both speed and correctness.
Common Pitfalls
- Assuming cached values will remain forever.
- Using cache as source of truth for business-critical data.
- Forgetting to set limits for large object workloads.
- Storing objects that are expensive to recreate but not handling cache misses.
Summary
NSCacheprovides memory-aware in-memory caching on Apple platforms.- Treat cache entries as optional and rebuildable.
- Use count and cost limits to control memory growth.
- Keep cache logic centralized for easier maintenance.
Related reading
- How to use python ray for independent computers (each have its username and password) via internet(distributed computation with ip address)?
- How to view the Folder and Files in GAC?
- How to write a scalable TCP/IP based server
- How to write more than 25 items/rows into Table for DynamoDB?
- how to use scipy.optimize.linear_sum_assignment in tensorflow or keras?
- How to use spot instance with amazon elastic beanstalk?
- How to use NSJSONSerialization
- How to use NSLocalizedString function with variables in Swift?

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.