views:

252

answers:

4

I have the following problem: In one flow of the execution I use alloc, and on the other flow, alloc is not needed. At the end of the if statement, in any case, I release the object. When I do 'build and Analize' I get an error: 'Incorrect decrement of the reference count of an object is not owned by the caller'.

How to solve that?

UIImage *image; 

int RandomIndex = arc4random() % 10;

if (RandomIndex<5) 
{
    image = [[UIImage alloc] initWithContentsOfFile:@"dd"];
}
else 
{
    image = [UIImage imageNamed:@"dd"];
}


UIImageView *imageLabel =[[UIImageView alloc] initWithImage:image];
[image release];
[imageLabel release];
+1  A: 

Instead of:

image = [UIImage imageNamed:@"dd"];

Do:

image = [[UIImage imageNamed:@"dd"] retain];
Dave DeLong
Or the other way, set the alloc'd one to autorelease.
chpwn
+6  A: 

You should retain the image in the second condition:

image = [[UIImage imageNamed:@"dd"] retain];

This way, both possible exits out of the condition will have an object with a reference count of one, from your point of view.

Otherwise, you are trying to release an already autoreleased object!

Chris Cooper
+1  A: 

imageNamed returns an autoreleased object. You can only release an object that you have ownership of.

This will work:

if (RandomIndex<5) 
{
    image = [[UIImage alloc] initWithContentsOfFile:@"dd"] autorelease];
}
else 
{
    image = [UIImage imageNamed:@"dd"];
}


UIImageView *imageLabel =[[UIImageView alloc] initWithImage:image];
[imageLabel release];
Jacob Relkin
+5  A: 

You can either do what others have suggested, or:

if (RandomIndex<5) 
{
    image = [UIImage imageWithContentsOfFile:@"dd"];
}
else 
{
    image = [UIImage imageNamed:@"dd"];
}

UIImageView *imageLabel =[[UIImageView alloc] initWithImage:image];
...
[imageLabel release];

This way, in both cases you are getting an autoreleased object image, which you do not then need to release yourself.

Emil