1

I want to caching image for 91 images. And All images are about 50mb. I see that a lot of memory is used up.

My code is here. What is the best way for efficient memory?

lG2Image[0] = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"background" ofType:@"png"]];
lG2Image[1] = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"myimage1" ofType:@"png"]];
lG2Image[2] = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"myimage2" ofType:@"png"]];
...


UIImageView* tmp;

for (int i=0; i<91; i++) {
    tmp = [[UIImageView alloc] initWithImage:lG2Image[i]];
    [_window addSubview:tmp];
    [tmp removeFromSuperview];
    tmp = nil;
}
iamugur
  • 11
  • 1
  • Why do you need to preload all 91 images into memory? Could you not just load one or two images ahead? – Pfitz Jul 22 '12 at 08:52
  • That's game level. All the images are in one level."Background, animations, effects, characters, objects.." Game's like that Mario. – iamugur Jul 22 '12 at 14:07

2 Answers2

0

You can reuse UIImageView.

The screen size of iPhone is fixed, that means the visable area is fixed. For example, if you want display 3 images on visable screen, you can just create 3 UIImageViews, when the view is moved, you can load new image according to current visible view's position, the images that's not on the visible screen can be released.

If you use UITableView, you can look this, LazyTableImages.

xda1001
  • 2,449
  • 16
  • 18
0

You have 2 options. Option 1, simply load game image elements "as needed", if this is a 2D game then load elements when they are about to come on screen. Option 2, decompress image data into raw pixel files in BGRA format and then use [NSData dataWithContentsOfMappedFile] and CGDataProviderCreateWithData() along with CGImageCreate() to create a CGImageRef that you will then wrap up as a UIImage. The second approach approach is very low level, but it avoids having to parse the image contents again every time the resource is accessed (the decompressed image data is stored in the file already). Also, Apple has optimized the way that CoreGraphics reads 2D images such that the entire memory contents can stay in main memory as opposed to being copied to graphics memory, so that means you can load a bunch of images with this method. If you can, I would try option #1 first, you likely will not need everything in memory at the same time. But option #2 can given you about 700 megs of working memory that your iOS application can map from files, far more than can be allocated as regular memory.

MoDJ
  • 4,309
  • 2
  • 30
  • 65