Objective-c – Memory issue in iPhone

iphoneobjective c

I am using single UIImageView object, allocated memory it once. But changing the image names multiple times.
The question is that,

A) one UIImageView object,allocated once and never changed image name.
e.g UIImageView *firstObj = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"blue.png"]];

B) another UIImageView object,allocated once and changed image names multiple times

e.g UIImageView *secondObj = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"blue.png"]];

//changed image name once,

secondObj.image = [UIImage imageNamed:@"green.png"];

 and so on....

which objects uses maximum memory or use equal memory?

which is the best way to use secondObj with minimum memory utilization?

please explain it briefly because i need to use number of image in my project and i want to avoid memory issue due to the images.

Best Answer

Reformatting your code, your second example is:

UIImageView *secondObj = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"blue.png"]];
// changed image name once
secondObj.image = [UIImage imageNamed:@"green.png"];
// and so on....

This code is fine. When you assign an image to an instance of UIImageView, it will increase the image's retain count by one. If an image is already assiged, it will release it first.

Since [UIImage imageNamed:...] will give you an object already marked for autorelease, you can continue to assign images as shown in the example with no memory leaks. Once the UIImageView releases the existing image, it will be collected by an Autorelease pool.

In terms of minimising memory usage, the [UIImage imageNamed:...] method does store the image in a small amount of application-wide cache memory that you don't exert any direct control over. The cache does have an upper limit limit, but you can't flush it to reclaim memory, so using it will increase your memory footprint as you fetch new UIImages.

You may want to consider avoiding this cache by using [UIImage imageWithData:...] to load your images, which is discussed in the Stackoverflow question [UIImage imageNamed…] vs [UIImage imageWithData…].

Related Topic