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.
Asked
Active
Viewed 522 times
2

Warpling
- 2,024
- 2
- 22
- 38
1 Answers
0
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.

Mattie
- 2,868
- 2
- 25
- 40
-
1This seems to be what I've discovered. This is a great answer to have on record for others! In my case the owner of the cache *is* responsible for object creation but creating these objects not only has a memory cost but a time cost. I found a way to make NSCache work for me by keeping a second reference to the objects currently in use that I check before hitting the cache. – Warpling Jan 08 '18 at 20:23
-
It's all a bit strange to me since it seems trivial to create your own NSCache like structure by evicting objects upon receiving memory pressure and backgrounding notifications but I guess the heuristics and `NSDiscardableContent` protocol make it useful in more complex cases. – Warpling Jan 08 '18 at 20:26
-
Yeah, it's totally possible to make a custom solution without too much work. I've only used it in very simple situations. I'm glad you found something that works for you! – Mattie Jan 10 '18 at 23:57