Question

I've got a series of buttons that each use a different image. Can I reuse a retained variable like this below:

// set images
UIImage *image = [[dice1 backgroundImageForState:UIControlStateHighlighted] retain];
[dice1 setBackgroundImage:image forState:(UIControlStateHighlighted|UIControlStateSelected)];
image = [dice2 backgroundImageForState:UIControlStateHighlighted];
[dice2 setBackgroundImage:image forState:(UIControlStateHighlighted|UIControlStateSelected)];
image = [dice3 backgroundImageForState:UIControlStateHighlighted];
[dice3 setBackgroundImage:image forState:(UIControlStateHighlighted|UIControlStateSelected)];
image = [dice4 backgroundImageForState:UIControlStateHighlighted];
[dice4 setBackgroundImage:image forState:(UIControlStateHighlighted|UIControlStateSelected)];
image = [dice5 backgroundImageForState:UIControlStateHighlighted];
[dice5 setBackgroundImage:image forState:(UIControlStateHighlighted|UIControlStateSelected)];
image = [dice6 backgroundImageForState:UIControlStateHighlighted];
[dice6 setBackgroundImage:image forState:(UIControlStateHighlighted|UIControlStateSelected)];
[image release];

or do I need to create a new UIImage for each image passed to each button's setBackgroundImage: and rely on autorelease rather than a retained UIImage. The above works but I'm not sure how setting the image for each of these buttons to the same image will effect the retain counts.

Was it helpful?

Solution

What you have there will leak (because you lose the reference to the first image) and crash (because you release an object you do not own). If you remove the -retain and the -release, your code will work just fine.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top