title: Instance caching in Objective C
body: <p>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 <code>release</code> method and when the retain count drops to one, I can remove the instance from cache and let it get deallocated.</p>
  
  <p>This works, but I am not comfortable mucking around the <code>release</code> 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.</p>
  
  <p><a href="http://developer.apple.com/documentation/Cocoa/Reference/NSHashTable_class/Introduction/Introduction.html" rel="nofollow noreferrer">NSHashTable</a> 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?</p>
  
  <hr>
  
  <p><em>Clarification:</em> I cannot afford to keep the instances in memory unless somebody really needs them, that is why I want to purge the instance from the cache when the last “real” user releases it.</p>
  
  <hr>
  
  <p><em>Better solution:</em> This was on the iPhone, I wanted to cache some textures and on the other hand I wanted to free them from memory as soon as the last real holder released them. The easier way to code this is through another class (let’s call it <code>TextureManager</code>). This class manages the texture instances and caches them, so that subsequent calls for texture with the same name are served from the cache. There is no need to purge the cache immediately as the last user releases the texture. We can simply keep the texture cached in memory and when the device gets short on memory, we receive the low memory warning and can purge the cache. This is a better solution, because the caching stuff does not pollute the <code>Texture</code> class, we do not have to mess with <code>release</code> and there is even a higher chance for cache hits. The <code>TextureManager</code> can be abstracted into a <code>ResourceManager</code>, so that it can cache other data, not only textures.</p>