2012-03-05 51 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

相關問題