Graphics Reference
In-Depth Information
The +imageNamed: caching mechanism is not public, so you have no fine-grained
control. For example, you cannot test to see whether an image has already been
cached before loading it, you cannot control the cache size, and you cannot remove
objects from the cache when they are no longer needed.
Custom Caching
Building a bespoke caching system is nontrivial. Phil Karlton once said, “There are only
two hard problems in computer science: cache invalidation and naming things.”
If we do decide to write our own image cache, how should we go about it? Let's look at the
challenges involved:
Choosing a suitable cache key —The cache key is used to uniquely identify an
image in the cache. If you are creating images at runtime, it's not always obvious how
to generate a string that will distinguish one cached image from another. In the case
of our image carousel, though, it's pretty straightforward because we can use either
the image filename or the cell index.
Speculative caching —If the effort of generating or loading data is high, you may
want to load and cache it before it is needed the first time. Speculative preloading
logic is inherently application specific, but in the case of our carousel, it is relatively
simple to implement, because for a given position and scroll direction, we can
determine exactly which images will be coming up next.
Cache invalidation —If an image file changes, how do we know that our cached
version needs to be updated? This is an extremely hard problem (as Phil Karlton
quipped), but fortunately it's not something we have to worry about when loading
static images from our application resources. For user-supplied images (which may
be modified or overwritten unexpectedly), a good solution is often to store a
timestamp for when the image was cached and compare it with the modified date of
the file.
Cache reclamation —When you run out of cache space (memory), how do you
decide what to throw away first? This may require you to write speculative
algorithms to determine the relative likelihood of cached items to be reused.
Thankfully, for the cache reclamation problem, Apple provides a handy general-
purpose solution called NSCache .
NSCache
NSCache behaves a lot like an NSDictionary . You can insert and retrieve objects from the
cache by key using the -setObject:forKey: and -object:forKey: methods, respectively.
The difference is that unlike a dictionary, NSCache automatically discards stored objects
when the system is low on memory.
Search WWH ::




Custom Search