正常情況下咆爽,我們重用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的創(chuàng)建并沒有包含任何重用信息,每次拖動tableview,都會一直創(chuàng)建不同的cell剂桥,當要顯示的cell很多時內存問題就顯露出來了。通過改進我們可以這樣實現(xiàn)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;