views:

72

answers:

1

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.

+2  A: 

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.

Dave DeLong
Ok, so the image is "owned" by the UIButton I don't need to worry about retaining it myself. App runs fine without as you indicated, so thanks!
Typeoneerror