Can't cheat the (NSCache) reaper

Ever write code that does something like this?

Where _cache is an NSMutableDictionary.

Well, be warned, if you decide to modernise the code to use an NSCache instance instead, it'll likely crash. In my testing NSCache doesn't always retain its objects immediately, so the above code can end up deallocating the object too quickly.

As Graham Lee points out, another difference between the two is that NSCache retains its keys rather than copying them (I find that's generally pretty handy). But you already knew that, right? If not, go read the docs.

Update: My ongoing experimentation suggests that rather than retaining objects later, NSCache simply sometimes decides to not bother storing an object at all. I presume this is an optimization so that while the cache is busy with some other work it avoids holding up your code. After all, it's a cache so you can always regenerate the data quite happily, right?

© Mike Abdullah 2007-2015