2012-03-05 88 views
0

我有一个自定义单元格,它有两个UILabel对象。我应该在哪里发布自定义单元格对象?

//AppEventCell.h 
#import <UIKit/UIKit.h> 

@interface AppEventCell : UITableViewCell 
{ 
    UILabel * titleLabel; 
    UILabel * periodLabel; 
} 
@property (nonatomic, retain) UILabel * titleLabel; 
@property (nonatomic, retain) UILabel * periodLabel; 
@end 


//AppEventCell.m 
#import "AppEventCell.h" 

@implementation AppEventCell 
@synthesize titleLabel, periodLabel; 

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier 
{ 
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; 
    if (self) { 
     titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 13, 275, 15)]; 
     [self.contentView addSubview:titleLabel]; 

     periodLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 33, 275, 15)]; 
     [self.contentView addSubview:periodLabel]; 
    } 
    return self; 
} 
@end 


- (AppEventCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"NoticeTableCell"; 

    AppEventCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 

     cell = [[AppEventCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    } 

    [cell.titleLabel setText:((NSString *)[[listArray objectAtIndex:indexPath.row] valueForKey:KEY_TITLE])]; 

[cell.periodLabel setText:((NSString *)[[listArray objectAtIndex:indexPath.row] valueForKey:KEY_PERIOD])]; 

return cell; 

}

这里有一个问题。我应该在哪里发布titleLabel和periodLabel?我想我应该自己释放他们。但是,AppEventCell中没有dealloc()(我创建了该方法,但从未调用过)。我将该版本放入CellForRowAtIndexPath中,但在单元重用时发生错误。

不应该释放对象吗?

回答

1

1)在这里,你应该将其添加为子视图后释放标签:

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier 
{ 
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; 
    if (self) { 
     titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 13, 275, 15)]; 
     [self.contentView addSubview:titleLabel]; 
     [titleLabel release]; 

     periodLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 33, 275, 15)]; 
     [self.contentView addSubview:periodLabel]; 
     [periodLabel release]; 
    } 
    return self; 
} 

2)dealloc方法应该呼吁你的细胞。它没有被调用是错误的。检查你正在释放您的tableView- (AppEventCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 是另一种内存泄漏:

cell = [[[AppEventCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 

马克新cellautoreleased对象。 3)如果电池重复使用([tableView dequeueReusableCellWithIdentifier:CellIdentifier];),那么您应该拨打releaseautorelease

+0

谢谢!!!!非常明确的答案。再次感谢。 – Ryan 2012-03-05 06:10:16

相关问题