Graphics Reference
In-Depth Information
Caching
When you have a large number of images to display, it isn't practical to load them all in
advance, but that doesn't mean that after you've gone to the trouble of loading them, you
should just throw them away as soon as they move offscreen. By selectively caching the
images after loading, you can avoid repeating the pop-in as users scroll back and forth
across images that they've already seen.
Caching is simple in principle: You just store the result of an expensive computation (or a
file that you've loaded from the flash drive or network) in memory so that when you need it
again, it's quicker to access. The problem is that caching is essentially a tradeoff—you gain
performance in return for consuming memory, but because memory is a limited resource,
you can't just cache everything indefinitely.
Deciding when and what to cache (and for how long) is not always straightforward.
Fortunately, most of the time, iOS takes care of image caching for us:
The +imageNamed: Method
We mentioned earlier that loading images using [UIImage imageNamed:] has the
advantage that it decompresses the image immediately instead of deferring until it's drawn.
But the + imageNamed: method has another significant benefit: It automatically caches the
decompressed image in memory for future reuse, even if you don't retain any references to
it yourself.
For the majority of images that you'll use in a typical iOS app (such as icons, buttons, and
background images), loading the image using the + imageNamed: method is both the
simplest and most performant approach. Images that you include in a nib file are loaded
using the same mechanism, so often you'll use it implicitly without even realizing.
The +imageNamed: method isn't a magic bullet, though. It's optimized for user interface
furniture and isn't appropriate for every type of image that an application might need to
display. Here are a few reasons why it may be a good idea to implement your own image
caching mechanism:
The +imageNamed: method only works for images that are stored in the application
bundle resources directory. In reality, most apps that display a lot of large images will
need to load them from the Internet, or from the user's camera roll, so +imageNamed:
won't work.
The +imageNamed: cache is used to store all of your application interface images
(buttons, backgrounds, and so on). If you fill the cache with large images like
photographs, you increase the chances that iOS will remove those interface images to
make room, which may lead to worse performance as you navigate around the app, as
those images will then have to be reloaded. By using a separate cache for your
carousel images, you can decouple their lifespan from the rest of your app images.
 
Search WWH ::




Custom Search