2010-08-02 86 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中发布的吗?