[英]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.