Making NSCache evict only unreferenced objects
Making NSCache evict only unreferenced objects
- Subject: Making NSCache evict only unreferenced objects
- From: Jens Alfke <email@hidden>
- Date: Fri, 17 Jun 2011 09:40:58 -0700
I have what seems like an excellent use case for NSCache, only it doesn’t have quite the behavior I need. And I’m having trouble thinking of how to tweak it to get that behavior.
In a nutshell: I want the cache to evict only objects that have no other references to them. So as long as something else has retained an object, it will stay in the cache. Only when that reference has been released will the object become a candidate for eviction. (I’m not using GC since this code will need to run on iOS.)
[Basically this is a cache of database records, where the dictionary key is the primary key and the value is a parsed version of the row data. I want to cache these to minimize database calls. I also want to ensure that the value objects are unique, i.e. there is never more than one value object for a particular primary key. NSCache alone won’t let me do that, since if an object gets evicted when there are still references to it, on the next fetch of that key I’ll re-fetch the row even though it’s still in memory.]
It seems like I could do this with some combination of NSCache and a weak NSMapTable*, but I haven’t figured out how. For example, I could add every object to both the cache and the table, then consult both tables when fetching; but that way the cache would be equally likely to evict objects that still have references, which is a waste. Or I could add an object to the cache only when its last external reference is removed, but that would require overriding -retain and -release, which I’m loath to do.
—Jens
* I realize NSMapTable only removes freed objects when GC is enabled; but it’s pretty easy to make my value class’s -dealloc method remove the object from the table, which gives the same result._______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden