自定义单元重用问题

时间:2012-07-16 13:40:15

标签: iphone objective-c ios

我正在将自定义单元格加载到表格视图中,并注意我的单元格未被正确重用。我正在使用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 个答案:

答案 0 :(得分: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;
}