正常情况下,我们重用cell的写法是这样
static NSString *CellIdentifier = @"Cell";
Cell *cell = (Cell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[[Cell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.titleLabel.text = [self.dataList objectAtIndex:indexPath.row];
return cell;
当我们用XIB构建Cell时,我们也许会这样写
static NSString *CellIdentifier = @"Cell";
Cell *cell = (Cell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([Cell class])
owner:self
options:nil] objectAtIndex:0];
//cell = [[[Cell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.titleLabel.text = [self.dataList objectAtIndex:indexPath.row];return cell;
我们可以看到cell的创建并没有包含任何重用信息,每次拖动tableview,都会一直创建不同的cell,当要显示的cell很多时内存问题就显露出来了。通过改进我们可以这样实现cell的重用
static NSString *CellIdentifier = @"Cell";
BOOL nibsRegistered = NO;
if (!nibsRegistered) {
UINib *nib = [UINib nibWithNibName:NSStringFromClass([Cell class]) bundle:nil];
[tableView registerNib:nib forCellReuseIdentifier:CellIdentifier];
nibsRegistered = YES;
}
Cell *cell = (Cell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.titleLabel.text = [self.dataList objectAtIndex:indexPath.row];
return cell;