NSCache Auto Delete Policy

What are some NSCache auto deletion policies? The Apple documentation does not mention them, and I experimentally discovered that NSCache did not respond to the memory warning.

+6
source share
2 answers

It is best to treat NSCache as a black box as much as possible.

From Caching and Clearing Memory (allocated by me):

When adding items to the cache, you can specify the value that should be associated with each key-value pair. Call the setTotalCostLimit: method to set the maximum value for the sum of all costs for cached objects. Thus, when an object is added that pushes totalCost above totalCostLimit , the cache can automatically supplant some of its objects to return below the threshold. This eviction process is not guaranteed, so trying to manipulate cost values ​​to achieve certain behaviors can be detrimental to cache performance. Pass 0 for cost if you have anything useful or use the setObject:forKey: method, which does not require passing a value.

Note. The account limit and total cost limit are not strictly enforced. That is, when the cache goes to one of its limits, some of its objects can be evicted immediately, later or never, all depending on the details of the cache implementation.

+7
source

NSCache does not respond to UIApplicationDidReceiveMemoryWarningNotification , but it automatically UIApplicationDidReceiveMemoryWarningNotification its objects in low-memory situations, obviously using some other mechanism.

While I previously suggested watching UIApplicationDidReceiveMemoryWarningNotification , this is not the case. No special handling is required for low memory situations, as NSCache handles this automatically.


Update:

As in iOS 7, NSCache not only does not respond to memory warnings, but also does not seem to properly clean itself of memory pressure (see NSCache crashes when the memory limit is reached (only on iOS 7) ).

I subclass NSCache observe UIApplicationDidReceiveMemoryWarningNotification and clear the cache when warning the memory:

 @interface AutoPurgeCache : NSCache @end @implementation AutoPurgeCache - (id)init { self = [super init]; if (self) { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeAllObjects) name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; } return self; } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; // if not ARC, also // // [super dealloc]; } @end 
+8
source

Source: https://habr.com/ru/post/917230/


All Articles