开发者

Retain, reuse, release?

开发者 https://www.devze.com 2022-12-27 01:07 出处:网络
I\'ve got a series of buttons that each use a different image. Can I reuse a retained variable like this below:

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:(UIControlStateHighl开发者_JAVA百科ighted|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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消