2012-07-16 84 views
0

我正在将自定义单元加载到表视图中,并注意到我的单元没有被正确地重新使用。我正在使用NSFetchedResultsController从Core Data中提取结果。自定义单元重用问题

我从笔尖加载单元格。单元标识符在界面构建器中设置。单元格似乎被重用,因为我每次滚动表格时都不会创建新的单元格。但是,单元格上的数据未正确显示。

// BeerCell.h 
@interface BeerCell : UITableViewCell 

@property (nonatomic, strong) IBOutlet UIImageView *beerImage; 
@property (nonatomic, strong) IBOutlet UILabel *displayBeerName; 
@property (nonatomic, strong) IBOutlet UILabel *displayBeerType; 

@end 

// BeerCell.m 
@implementation BeerCell 

@synthesize beerImage; 
@synthesize displayBeerName; 
@synthesize displayBeerType; 

@end 

// Code where i'm setting up the cells for the tableView 

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

    BeerCell *cell = (BeerCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if (cell == nil) { 

     NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"BeerCell" owner:self options:nil]; 

     for (id currentObject in topLevelObjects){ 

      if ([currentObject isKindOfClass:[UITableViewCell class]]){ 
       cell = (BeerCell *) currentObject; 
       break; 
      } 
     } 

     [self configureCell:cell atIndexPath:indexPath]; 

    }   

    return cell; 
} 

- (void)configureCell:(BeerCell *)cell 
      atIndexPath:(NSIndexPath *)indexPath 
{ 
    Beer *beer = (Beer *) [self.fetchedResultsController objectAtIndexPath:indexPath]; 
    cell.displayBeerName.text = beer.name; 
} 

回答

1

在if块之外进行configureCell函数调用。

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

    BeerCell *cell = (BeerCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if (cell == nil) { 

     NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"BeerCell" owner:self options:nil]; 

     for (id currentObject in topLevelObjects){ 

      if ([currentObject isKindOfClass:[UITableViewCell class]]){ 
       cell = (BeerCell *) currentObject; 
       break; 
      } 
     } 
    }   
    [self configureCell:cell atIndexPath:indexPath]; 
    return cell; 
} 
+0

我不敢相信我没有看到。在旁注中,是否需要在Cell自定义类中实现prepareForUse? – Vikings 2012-07-16 13:47:34

+0

查看链接:http://stackoverflow.com/questions/5162700/prepareforreuse – Apurv 2012-07-16 13:50:33

相关问题