ioscachingnscache

NSCache releases objects even when there are strong references to them?


I've setup a basic NSCache and am storing NSObject subclassed objects. I'm observing these objects being released from the cache (upon backgrounding the app) even when there are 1+ other strong references to them (verified with memory debugger). Am I missing something here? As I understood, NSCache would only release objects under memory pressure if there were no remaining references to them.


Solution

  • I think you are seeing that NSCache doesn't trace through the ownership graph to see if releasing an object will actually save memory. It does the release based on it's own local heuristics.

    It might make more sense to think about your use of NSCache in this situation. If there are other strong refs, is the owner of the cache not responsible for the creation of the object? Is it the lookup you are trying to cache?

    I have only used NSCache in cases where the object creation is expensive, but can be done at any time and will not impact my object graph.