Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-c - benefits of using NSCache over a static NSMutableDictionary?

So the NSCache object should stay alive in order to keep the cached data, that means the same object that was used to store data, has to be used to retrieve data.

  • So the question is what's the point of using NSCache over a singleton NSDictionary that holds my data?
  • What's the preferred way to use NSCache? static field? inherit it and create a singleton?
like image 520
aryaxt Avatar asked May 08 '12 16:05

aryaxt


People also ask

Is NSCache thread safe?

One more thing about NSCache is, it is thread safe. We can access it from any thread without worrying about managing threads while accessing NSCache. You can set & get name for cache. The default value is an empty string (“”).

What is NSCache?

A mutable collection you use to temporarily store transient key-value pairs that are subject to eviction when resources are low.


1 Answers

A cache has a number of quirks that make it work well as a cache while being poorly suited to use as a general purpose collection. As noted in the docs:

NSCache objects differ from other mutable collections in a few ways:

  • The NSCache class incorporates various auto-removal policies, which ensure that it does not use too much of the system’s memory. The system automatically carries out these policies if memory is needed by other applications. When invoked, these policies remove some items from the cache, minimizing its memory footprint.
  • You can add, remove, and query items in the cache from different threads without having to lock the cache yourself.
  • Retrieving something from an NSCache object returns an autoreleased result.
  • Unlike an NSMutableDictionary object, a cache does not copy the key objects that are put into it.

These features are necessary for the NSCache class, as the cache may decide to automatically mutate itself asynchronously behind the scenes if it is called to free up memory.

like image 130
Chuck Avatar answered Oct 03 '22 19:10

Chuck