工作一年多的時間,本以為對Cell的復(fù)用已經(jīng)理解透徹了,然而通過這次版本的迭代開發(fā),發(fā)現(xiàn)自己遠沒有達到透徹的標準。于是抽出時間做一下小結(jié):
按照平時的方式,我們創(chuàng)建使用一個UITableViewCell常見的方式是:
UITableViewCell *cell = [[UITableViewCell alloc] init];
cell.textLabel.text = @"hello";...
但是這種方式有個弊端,當創(chuàng)建大量的cell的時候容易浪費內(nèi)存。比如也許剛開始我們我們要創(chuàng)建300個cell的時候還好,因為只有當這個cell真正顯示在屏幕上的時候才會被創(chuàng)建(蘋果幫我們做了優(yōu)化,只有當cell即將被顯示到屏幕上才會調(diào)用tableView:cellForRowAtIndexPath:
)。但是當我們在屏幕上滑動tableView的時候依然存在問題,因為在我們滑動的過程中會存在cell的頻繁創(chuàng)建與銷毀。
幸好蘋果提供了更加簡潔的方式來創(chuàng)建cell,如下所示:
方式一:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString * const cellIdentifier = @"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
cell.backgroundColor = [UIColor greenColor];
}
cell.textLabel.text = @"hello";
return cell;
}
tableView首先會去緩存池中取綁定cellIdentifier標識的cell,如果取到則返回;如果取不到,則會創(chuàng)建一個新的cell并綁定標識。在使用的過程中一定要注意cell屬性設(shè)置的時機,一般在if條件括號內(nèi)的,是cell的固有屬性,當這個cell被取出重新復(fù)用的時候,會帶有這個屬性。而if條件判斷之外,則會隨著每列cell的重新加載(無論是復(fù)用還是創(chuàng)建),會重新賦值。
- 方式二:注冊cell,然后直接從緩存獲取
這種方式一般會用在自定義cell的加載中,也就是我們既可以通過一個類也可以通過一個nib文件來加載cell。當注冊一個cell并綁定標識后,tableView會先從緩存池中取綁定的標識的cell,若是沒有系統(tǒng)則會自動創(chuàng)建一個cell,并綁定標識。NSString * const cellIdentifier = @"CellIdentifier"; - (void)viewDidLoad { [super viewDidLoad]; [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cellIdentifier]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; cell.textLabel.text = @"hello"; return cell; }