我有一系列按钮,每个按钮使用不同的图像。我可以重复使用如下所示的保留变量:
// 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。以上工作,但我不确定如何将这些按钮的图像设置为同一图像将影响保留计数。
答案 0 :(得分:3)
你所拥有的东西会泄漏(因为你失去了对第一张图像的引用)并且崩溃(因为你release
是你不拥有的对象)。如果您移除-retain
和-release
,您的代码就可以正常使用。