Instance caching in Objective C
I want to cache the instances of a certain class. The class keeps a dictionary of all its instances and when somebody requests a new instance, the class tries to satisfy the request from the cache first. There is a small problem with memory management though: The dictionary cache retains the inserted objects, so that they never get deallocated. I do want them to get deallocated, so that I had to overload the `release` method and when the retain count drops to one, I can remove the instance from cache and let it get deallocated.

This works, but I am not comfortable mucking around the `release` method and find the solution overly complicated. I thought I could use some hashing class that does not retain the objects it stores. Is there such? The idea is that when the last user of a certain instance releases it, the instance would automatically disappear from the cache.

[NSHashTable][1] seems to be what I am looking for, but the documentation talks about “supporting weak relationships in a garbage-collected environment.” Does it also work without garbage collection?


  [1]: http://developer.apple.com/documentation/Cocoa/Reference/NSHashTable_class/Introduction/Introduction.html
Instance caching in Objective C
===

I want to cache the instances of a certain class. The class keeps a dictionary of all its instances and when somebody requests a new instance, the class tries to satisfy the request from the cache first. There is a small problem with memory management though: The dictionary cache retains the inserted objects, so that they never get deallocated. I do want them to get deallocated, so that I had to overload the `release` method and when the retain count drops to one, I can remove the instance from cache and let it get deallocated.

This works, but I am not comfortable mucking around the `release` method and find the solution overly complicated. I thought I could use some hashing class that does not retain the objects it stores. Is there such? The idea is that when the last user of a certain instance releases it, the instance would automatically disappear from the cache.

[NSHashTable][1] seems to be what I am looking for, but the documentation talks about “supporting weak relationships in a garbage-collected environment.” Does it also work without garbage collection?


  [1]: http://developer.apple.com/documentation/Cocoa/Reference/NSHashTable_class/Introduction/Introduction.html