extracts from 《Beginning iPhone Games Development》
When we’re dealing with development of a game, it is likely loading too many images orother resources is causing the memory problem. There are ways to architect your imageloading so that you can release memory taken up by your images. Listings 3–32 and 3–33 show a simple implementation of a caching image loader you can use in your apps.
Listing 3–32.The interface to the custom image loader, named ImageCache.h#import <Foundation/Foundation.h>
@interface ImageCache : NSObject {
}
+ (UIImage*)loadImage:(NSString*)imageName;
+ (void)releaseCache;
@end
Listing 3–33.The implementation to the custom image loader, named ImageCache.m#import "ImageCache.h"
@implementation ImageCache
static NSMutableDictionary *dict;
+ (UIImage*)loadImage:(NSString*)imageName
{
if (!dict) dict = [[NSMutableDictionary dictionary] retain];
UIImage* image = [dict objectForKey:imageName];
if (!image)
{
NSString* imagePath = [[NSBundle mainBundle]
pathForResource:imageName
ofType:nil];
image = [UIImage imageWithContentsOfFile:imagePath];
if (image)
{
[dict setObject:image forKey:imageName];
}
}
return image;
}
+ (void)releaseCache {
if (dict) {
[dict removeAllObjects];
}
}
@end
To use the caching image loader, call theloadImage:class method of theImageCacheclass, passing in the image file name as a parameter. To release all the images held inthe cache, call the releaseCacheclass method.
This basic code gets the job done, but it is an all-or-nothing approach. You cache everyimage, and when the operating system complains memory is low, you unload everyimage from the cache. You could easily modify this code to let you keep severaldifferent caches rather than one universal cache. That way, you could use a differentcache for each view in your app, and unload images only from views that are no longeron screen.