Is there a more elegant solution for this question?
I have about 70 .png images I want to load and randomly pull from an array when a button is pressed. (Up to 50 images could be on screen at once and each is 40-68kbs in size with dimensions of 150X215, obviously there will be over lap and covered images behind foreground images at times) Should I use the following example to pull that off?
EXAMPLE:
-(void)viewDidLoad {
UIImage *dogImage = [UIImage imageNamed: @"dog.png"];
UIImage *catImage = [UIImage imageNamed: @"cat.png"];
// And so on 68 more times followed by....
for (int i = 1; i <= 70; i++) {
UIImageView *dogView = [[UIImageView alloc]initWithImage:dogImage];
UIImageView *catView = [[UIImageView alloc]initWithImage:catImage];
// And so on 68 more times followed by....
NSArray *animalArray = [[NSArray alloc] initWithObjects: dogView, catView, nil];
// And so on 68 more times ending the array with ,nil
// other code and and release calls, etc...
}
}
Is this fine for performance or am I going to crash the app at launch or soon after? The
Anyone alternatives to doing it this way?
Also, you need to remember that the size of the image you’re quoting is its compressed size. As soon as that image is used in a view, it’ll be uncompressed to be drawn to the graphics context. The uncompressed size of 70 images is going to be a hell of a lot more than a few megabytes.
If you load them all that the same time you’ll likely crash the app with an out of memory error.
I suggest only storing the image filenames in the array and only loading the image when it’s actually required.
Also, there are some differences in the way that
UIImageloads image data depending on what method you use to load the image. I’m not confident enough in my memory of this situation to write down the exact differences. The basic idea is thatimageNamed:will load and cache the image for you, while (I think) initWithContentsOfFile will load the image data on demand, saving you some memory until the very last minute when the image is needed.