NSCache, does removeAllObjects release the memory usage? I'm using ARC

3.5k Views Asked by At

I'm using ARC and NSCache which is created and stored on my app delegate. Then I call it from the controllers trough the app delegate. The NSCache stores images as they are loaded from an url and the memory usage goes up really quick. When I check the profiler for real memory usage, my app reaches even 320 MB of memory usage but on allocations it says it has just allocated 20-30 MB.

On my app delegate I set the cache as follows (it is an ivar):

cache = [[NSCache alloc] init];
[cache setCountLimit:100];
[cache setTotalCostLimit:1500000];
[cache setEvictsObjectsWithDiscardedContent:YES];

I implemented a button to experiment with NSCache and when I click on it it calls:

- (IBAction)eraseCache:(id)sender {
    [[appDelegate cache] removeAllObjects];
}

On the profiler, the memory used does not go down, but it actually starts to get the images again, so I know the objects where removed. How can I release this memory usage at will using ARC? How can I get the size of my cache to know when to release it?

1

There are 1 best solutions below

6
On BEST ANSWER

In ARC, once there are no pointers to an object, it's automatically released. If the only pointers you had to the object were in the cache, then they have been released.

Note that you don't actually have to remove the objects; if you assign the pointer to a new object (with the result that it no longer points at the old object) then the old object is deallocated.

Ex:
NSArray *array = [NSArray new];
array = [NSArray new]; //the original array gets deallocated because nothing points to it.

From the NSCache Class Reference:

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.