簡體   English   中英

我可以解決的崩潰,但我不明白為什么會發生這種情況

[英]A crash I can fix, but I don't understand why it's happening

我有一個scrollview。 我在此滾動視圖中添加了一個按鈕,然后將其釋放。

UIButton * saveButton = [UIButton buttonWithType:UIButtonTypeCustom];
saveButton.frame = CGRectMake(415.0, 473, 80, 38);
saveButton.titleLabel.font = [UIFont fontWithName:@"Heiti TC" size:24];
[saveButton setTitle:@"" forState:UIControlStateNormal];
[saveButton setContentEdgeInsets:UIEdgeInsetsMake(2, 0, 0, 0)];
saveButton.backgroundColor = [UIColor clearColor];
[saveButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal ];
[saveButton setBackgroundImage:[UIImage imageNamed:@"save.png"] forState:UIControlStateNormal];
[saveButton addTarget:self action:@selector(save) forControlEvents:UIControlEventTouchUpInside];
saveButton.hidden = NO;
[self.scrollview addSubview:saveButton];
[saveButton release];

當視圖出現在屏幕上時應用程序崩潰,我嘗試觸摸屏幕的任何部分。

如果我發表評論

[saveButton release];

該應用程序完美。

我想按鈕的保留計數會在我添加到滾動視圖后增加,所以我可以安全地釋放按鈕。

這里發生了什么? 是否向滾動視圖添加內容與將其添加到主視圖(如下所示)不同?

[self.view addSubview:saveButton];

buttonWithType:是一個方便的構造函數,因此它已經創建了一個自動釋放的實例,並且不需要釋放該對象。

這意味着以下代碼行是一個錯誤:

[saveButton release];

您不應發送release ,因為該實例已經自動釋放。

有關詳細信息,請查看UIButton參考

UIButton * saveButton = [UIButton buttonWithType:UIButtonTypeCustom];

根據內存管理規則,此代碼返回一個自動釋放的對象,當您使用它完成工作時,您不必釋放它。 當您將其添加為視圖的子視圖時,您要添加它的視圖將保留它,並且您不對其內存管理負責。

這里沒有使用alloc/init/new ,所以這將是自動釋放的。 如果你有這樣的東西UIButton *savebutton = [[UIButton alloc]init]; 然后你將不得不使用像: [saveButton release];

這里的問題是

[UIButton buttonWithType:UIButtonTypeCustom]

method返回一個自動釋放的對象,該對象僅由自動釋放池保留(它將在當前事件隊列的末尾釋放該對象)。 這意味着你沒有對它的所有權(它沒有保留)。 將其添加到滾動視圖會將保留計數加1,但是您可以通過發送釋放消息立即在下一行中銷毀它。

執行此操作的正確方法是刪除釋放調用(並且您將完全清楚內存管理)。

您可以在此處閱讀有關iOS內存管理的更多信息

你沒有為按鈕對象分配內存。 所以你怎么能釋放它。

UIButton * saveButton = [UIButton buttonWithType:UIButtonTypeCustom];

您調用了一個靜態方法,它本身負責內存管理。 這是應用程序崩潰的唯一原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM