Graphics Reference
In-Depth Information
The algorithm that NSCache uses to determine when to discard objects is not documented,
but you can provide hints for how you would like it to behave using the -setCountLimit:
method to set the total cache size and -setObject:forKey:cost: to specify a “cost” value
for each stored object.
The cost is a numeric value that you can assign to an object to indicate the relative effort of
recreating it. If you assign a large cost for large images, the cache knows that these are
more expensive objects to store and that discarding a “costly” object will potentially have a
greater performance impact than a “cheap” one. You can specify the total cache size in
terms of cost instead of item count by using -setTotalCostLimit: .
NSCache is a general-purpose caching solution, and we could probably create a custom
caching class that is better optimized for our specific carousel if we had to. (For example,
we could determine which images to release first based on the difference between the
cached image index and the currently centered index.) But NSCache should be sufficient for
our current caching requirements; we don't want to indulge in premature optimization.
Let's extend our carousel example with an image cache and a basic speculative preloading
implementation and see if that improves the pop-in effect for new images (see Listing
14.5).
Listing 14.5 Adding Caching and Speculative Loading
#import "ViewController.h"
@interface ViewController () < UICollectionViewDataSource >
@property ( nonatomic , copy ) NSArray *imagePaths;
@property ( nonatomic , weak ) IBOutlet UICollectionView *collectionView;
@end
@implementation ViewController
- ( void )viewDidLoad
{
//set up data
self . imagePaths =
[[ NSBundle mainBundle ] pathsForResourcesOfType : @"png"
inDirectory : @"Vacation Photos" ];
//register cell class
[ self . collectionView registerClass :[ UICollectionViewCell class ]
forCellWithReuseIdentifier : @"Cell" ];
}
- ( NSInteger )collectionView:( UICollectionView *)collectionView
Search WWH ::




Custom Search