2010-08-02 88 views
0

這是我不明白的東西。看看這個方法(複製自http://blog.blackwhale.at/2009/07/uibutton-in-uitableview-footer/iphone - 會泄漏嗎?

看到footerView被分配在代碼的開頭,並且從未被釋放。 據我所知,該對象應該是autoreleased或至少釋放後使用一個普通的情況下,但由於這種方法是自動運行的表,當它們被建立時,這個視圖的確切位置將被釋放...

還是會泄漏?我看過蘋果的代碼樣例,所以我想這個對象正在某處發佈......但是在哪裏?

// custom view for footer. will be adjusted to default or specified footer height 
// Notice: this will work only for one section within the table view 
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section { 

    if(footerView == nil) { 
     //allocate the view if it doesn't exist yet 
     footerView = [[UIView alloc] init]; 

     //we would like to show a gloosy red button, so get the image first 
     UIImage *image = [[UIImage imageNamed:@"button_red.png"] 
    stretchableImageWithLeftCapWidth:8 topCapHeight:8]; 

     //create the button 
     UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
     [button setBackgroundImage:image forState:UIControlStateNormal]; 

     //the button should be as big as a table view cell 
     [button setFrame:CGRectMake(10, 3, 300, 44)]; 

     //set title, font size and font color 
     [button setTitle:@"Remove" forState:UIControlStateNormal]; 
     [button.titleLabel setFont:[UIFont boldSystemFontOfSize:20]]; 
     [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; 

     //set action of the button 
     [button addTarget:self action:@selector(removeAction:) 
         forControlEvents:UIControlEventTouchUpInside]; 

     //add the button to the view 
     [footerView addSubview:button]; 
    } 

    //return the view for the footer 
    return footerView; 
} 

謝謝。

+3

iPhone可能會泄漏,但iPad是超強吸水性的。 – JasCav 2010-08-02 17:29:00

回答

2

看作footerView是這個類的一個實例變量,這段代碼是正確的。 footerView不是自動回收(無論如何),所以只要你不release它(因爲你「擁有」/通過分配它保留它)它將繼續存在。在這個類的dealloc方法中,適當的地方可以做到這一點。

只要你這樣做,這段代碼看起來是正確的。 :)

+0

但假設在大部分時間內,一個給定的類永遠不會被釋放,同時一個表會被多次構建。每次構建這個表並顯示一個新的footerView將被創建,對吧?所以這將是一堆泄漏的footerViews,並且當這個類不在時,最後一個會被釋放,對吧? (假設表不是一個班級,而是一個班級的一部分)...... – SpaceDog 2010-08-02 17:25:26

+0

@Digital如果你多次實例化這個班級,那麼你會創建多個footerviews。但是,如果此類僅實例化一次,那麼只會有一個footerview。但是,這有點(我認爲)。只要釋放footerview,當類被釋放時,你的內存管理是正確的。 – 2010-08-02 17:27:55

+0

ahhh以及如何通過方法在本地創建視圖時如何取消分配dealloc方法的視圖?我應該存儲一個在dealloc上使用的引用嗎?或者只是成爲課程的一部分,將會使視圖自動發佈? – SpaceDog 2010-08-02 17:29:52

1

footerView是一個實例變量。它是在課堂的dealloc中發佈的嗎?