I am using NSCache to implement caching in my app. I want to add expiration to it so it will obtain new data after some time. What are the options and what's the best approach?
Should I look at the timestamp when the cache is accessed and invalidate it then? Should the cache automatically invalidate itself by using a fixed interval timer?
Another solution would be to set an expire time when setting an object and compare against the expire time for an object.
For example:
Usage
Interface
Implementation
This would be a bad solution, because you might add something seconds before the timer fires. The expiry should be based on the specific item's age. (It would, of course, be possible to conditionally invalidate items using a timer; see the comments on this answer.)
Here's an example. I thought about subclassing
NSCache
, but decided it was simpler to use composition.Interface
Implementation
Notes
setObject:forKey:cost:
since the NSCache documentation all but tells you not to use it.expiringCacheItemDate
. I thought about usingrespondsToSelector:
for this, but you could add an object that doesn't respond to that too, since NSCache takesid
and notNSObject
.Sample code