UITableView单元格返回nil属性值

我有以下几点:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { if(indexPath.row==0) { static NSString *CellID = @"FlourishCustomCell"; FlourishCustomCell *cell = (FlourishCustomCell *) [tableView dequeueReusableCellWithIdentifier:CellID]; if (cell == nil) { cell = [[[FlourishCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellID] autorelease]; cell.frame = CGRectMake(0, 0.0, 292.0, 30); } id <NSFetchedResultsSectionInfo> sectionInfo = [[appDelegate.fetchedResultsController sections] objectAtIndex:indexPath.section]; NSLog(@"DATE:%@", [sectionInfo name]); //Output: March 25 cell.dateLabel.text=[sectionInfo name]; NSLog(@"header cell:%@", cell.dateLabel.text); //Output:header cell:(null) return cell; } else { static NSString *CellIdentifier = @"IdeaCustomCell"; IdeaCustomCell *cell = (IdeaCustomCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[IdeaCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; cell.frame = CGRectMake(0, 0.0, 292.0, 70); } [self configureCell:cell atIndexPath:[self newIndexPathForIndexPath:indexPath]]; return cell; } } 

这些单元格对于else部分( IdeaCustomCell )来说显示效果良好,但是对于一些非常令人沮丧的原因,当我设置FlourishCelldateLabel ,然后立即尝试访问该值时,我得到一个null值,尽pipe我只是设置它! 单元格不显示在屏幕上。

我试着在FlourishCustomCell类中重写dateLabel的setter方法,并且在那里放了一个NSLog语句,但是由于某种原因它永远不会被调用。

我完全不知道是什么原因造成的。 我的意思是我正在分配权利,但它仍然给我空。 有任何想法吗?

你需要初始化标签

解决scheme1:在代码中初始化单元格

 @interface FlourishCustomCell : UITableViewCell @property (nonatomic, retain) UILable * dateLabel; @end @implementation FlourishCustomCell @synthesize dateLabel = _dateLabel; - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) { _dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,0,300,50)]; [self.contentView addSubview:_dateLabel] } return self; } @end 

解决scheme2:从笔尖初始化单元

 @interface FlourishCustomCell : UITableViewCell @property (nonatomic, retain) UILable * dateLabel; @end @implementation FlourishCustomCell @synthesize dateLabel = _dateLabel; - (id)init { self = [[[[NSBundle mainBundle] loadNibNamed:@"YOUR_NIB_NAME" owner:nil options:nil] lastObject] retain]; return self; } @end 

编辑 :哎呀,忘记在初始化方法返回自我,更新答案

我用同样的问题,使用笔尖,这对我有效

 - (UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *identifier = @"Cell"; CustomCell *cell = (CustomCell*)[tableView dequeueReusableCellWithIdentifier:identifier]; if (!cell) { NSString* nibFile = @"NibForCell"; NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed: nibFile owner:nil options: nil]; cell = [topLevelObjects objectAtIndex: 0]; } cell.cellText.text = @"test"; return cell; } 

只要确保在nib的属性中设置了重用标识符