0
votes

I have potential memory leak problem from the UIImage objects. Code is as below. Please help.


UIImage *image = nil;

if (x == 0) {
    image = [UIImage imageWithCGImage:cg1];
} else {
    image = [UIImage imageWithCGImage:cg2];
}

UIImageView *imageView = [[UIImageView alloc] initWithImage:image];

[image release]; 

I tried to release UIImage object after if-else block, but Xcode warned about "Incorrect decrement of the reference count of an object that is not owned at this point by the caller",

If I remove the [image release], it shows "Potential leak of an object allocated on line ...".

How to solve the problem ?

Thanks.

3

3 Answers

3
votes

The problem is that [UIImage new] is the same as [[UIImage alloc] init], so you already have an retained instance. Then you throw the pointer to the instance away by calling [UIImage imageWithCGImage:], which returns an autoreleased instance that you don't need to retain!

The solution is throwing the [UIImage new] out of your code, as well as the [image release] at the end.

0
votes

You're allocating a new instance of a UIImage object using the new method and assigning it to the image variable. Then you are immediately leaking that instance by assigning a different instance to the variable using the imageWithCGImage: method.

You don't need to do UIImage *image = [UIImage new]; at the beginning. You can simply declare your variable without assigning any instances to it. Good practice would be to assign nil to it initially.

When you do this you won't need to release the image object later because imageWithCGImage returns an autoreleased object.

0
votes
UIImage *image = nil;

if (x == 0) {
    image = [UIImage imageWithCGImage:cg1];
} else {
    image = [UIImage imageWithCGImage:cg2];
}

UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
// Some code
[imageView release];

You take ownership of the object imageView and not image. So u should release imageView and not image. Take a look at Object ownership in Apple's Memory Management guide