保留,重用,发布?

时间:2010-04-17 20:30:16

标签: objective-c retain

我有一系列按钮,每个按钮使用不同的图像。我可以重复使用如下所示的保留变量:

// 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];

或者我是否需要为传递给每个按钮的UIImage的每个图像创建一个新的setBackgroundImage:,并依赖于自动释放而不是保留的UIImage。以上工作,但我不确定如何将这些按钮的图像设置为同一图像将影响保留计数。

1 个答案:

答案 0 :(得分:3)

你所拥有的东西会泄漏(因为你失去了对第一张图像的引用)并且崩溃(因为你release是你不拥有的对象)。如果您移除-retain-release,您的代码就可以正常使用。