[英]How to release background image of UIButton?
谁能告诉我如何释放在 UIButton 中用作背景图像的图像。 我使用以下代码创建了自定义按钮,但我无法释放 UIImage 的 memory,它在 UIButton 中设置了背景图像。 这是我用来创建 UIButton 的代码
`
for (int index=0;index<10; index++)
{
UIImage *image=[[UIImage alloc] initWithData:imageData];
CGRect frame = CGRectMake(xValue, 10, 50, 50);
UIButton *button = [[UIButton alloc] initWithFrame:frame];
[button addTarget:self action:@selector(onClickImgButton:)forControlEvents:UIControlEventTouchUpInside];
[button setTag:index];
[button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[button setImage:image forState:UIControlStateNormal];
[button.layer setCornerRadius:10.0f];
[button.layer setMasksToBounds:YES];
[button.layer setBorderWidth:3.0f];
[button.layer setBorderColor:[[UIColor lightGrayColor] CGColor]];
image=nil;
[image release];
[horizontalScrollView addSubview:button];
button=nil;
[button release];
xValue=xValue+60;
cx +=60;
}
`
首先,你混合了你的 image=nil; [图片发布];
命令,你应该先释放,而不是将指针设置为 nil。 现在你将“释放”发送到 nil 并且没有任何反应。 顺便说一句,您正在为按钮做同样的事情。
现在如果你想让图像从 memory 中释放出来,只要它被按钮使用,你就不能这样做。 因此,您必须从 memory 中释放按钮(在这种情况下,通过修复释放并将指针设置为 nil,并从其超级视图中删除按钮)或执行
[button setImage:nil forState:UIControlStateNormal];
应该将保留计数设置为 0 并最终解除分配图像
在上面,您将release
消息发送到nil
。 一般来说,反转这个,即
[image release];
image = nil;
这里也犯了类似的错误。
但是,由于UIButton
实例是(根据快速查看UIButton.h
)保留图像,因此执行image = nil
即只是
[image release];
是正确的。 您目前正在对给定的 object 如何设置其属性之一做出很大的假设。
例如,想象一下释放 UIButton 实例时会发生什么。 当您早已将图像设置为nil
时,它如何向您保留的图像发送release
? 该按钮发现自己保留了一个零图像。 它将面临你给自己的同样问题——将release
发送为零!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.