在使用UITableView控件的時候,datasource的代理方法經常會使用到下面的方法來加載UITableView的數據顯示
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CustomCellIdentifier = @"CustomCellIdentifier";
DiscountProductCell * cell= (DiscountProductCell*)[tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier];
if (cell == nil) {
NSArray * nib = [[NSBundle mainBundle] loadNibNamed:@"DiscountProductCell" owner:self options:nil] ;
cell = [nib objectAtIndex:0];
}
cell.item = mPushItem;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UIImageView *backgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"list"]] autorelease];
cell.backgroundView = backgroundView;
UIImageView *accessoryView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ad1"]] autorelease];
[accessoryView setFrame:CGRectMake(0.0f, 0.0f, CATEGORY_CELL_AC_WIDTH, CATEGORY_CELL_AC_HEIGHT)];
cell.accessoryView = accessoryView;
return cell;
}
代碼中 DiscountProductCell * cell= (DiscountProductCell*)[tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier];是每個
cellForRowAtIndexPath方法都必須用到的。其中dequeueReusableCellWithIdentifier的意義是什么呢?
tableView實現是這樣的,它並不創建所有行,比如你的表格數據有100行,但是屏幕上的空間只夠顯示10行,那么tableView只會創建10個左右的cell,當你滾動時,有些行會被遮住,這些被遮住的行就會被回收放入它的回收空間,而將要出現的行會首先在回收空間查找是否有空閑的cell,如果找到就使用,這樣避免了創建cell帶來的開銷,節省空間和時間。這時的cell里的內容是舊的,你必需更新它的內容為將要出現的行的內容。