iOS extracts: Managing Memory with a Custom Image Loader

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. 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值