創(chuàng)建UITableViewController子類的實(shí)例后,IDE生成的代碼中有如下段落:
- - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
- static NSString *CellIdentifier = [NSString stringWithFormat:@"Cell"];
- UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
- if (cell == nil) {
- cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
- }
-
- return cell;
- }
這里就涉及了TableView的重用機(jī)制,為了做到顯示和數(shù)據(jù)分離,IOS tableView的實(shí)現(xiàn)并且不是為每個(gè)數(shù)據(jù)項(xiàng)創(chuàng)建一個(gè)tableCell。而是只創(chuàng)建屏幕可顯示最大個(gè)數(shù)的cell,然后重復(fù)使用這些cell,對(duì)cell做單獨(dú)的顯示配置,來達(dá)到既不影響顯示效果,又能充分節(jié)約內(nèi)容的目的。下面簡(jiǎn)要分析一下它的實(shí)現(xiàn)原理。
重用實(shí)現(xiàn)分析
查看UITableView頭文件,會(huì)找到NSMutableArray* visiableCells,和NSMutableDictnery* reusableTableCells兩個(gè)結(jié)構(gòu)。visiableCells內(nèi)保存當(dāng)前顯示的cells,reusableTableCells保存可重用的cells。
TableView顯示之初,reusableTableCells為空,那么tableView dequeueReusableCellWithIdentifier:CellIdentifier返回nil。開始的cell都是通過[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]來創(chuàng)建,而且cellForRowAtIndexPath只是調(diào)用最大顯示cell數(shù)的次數(shù)。
比如:有100條數(shù)據(jù),iPhone一屏最多顯示10個(gè)cell。程序最開始顯示TableView的情況是:
1. 用[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]創(chuàng)建10次cell,并給cell指定同樣的重用標(biāo)識(shí)(當(dāng)然,可以為不同顯示類型的cell指定不同的標(biāo)識(shí))。并且10個(gè)cell全部都加入到visiableCells數(shù)組,reusableTableCells為空。
2. 向下拖動(dòng)tableView,當(dāng)cell1完全移出屏幕,并且cell11(它也是alloc出來的,原因同上)完全顯示出來的時(shí)候。cell11加入到visiableCells,cell1移出visiableCells,cell1加入到reusableTableCells。
3. 接著向下拖動(dòng)tableView,因?yàn)閞eusableTableCells中已經(jīng)有值,所以,當(dāng)需要顯示新的cell,cellForRowAtIndexPath再次被調(diào)用的時(shí)候,tableView dequeueReusableCellWithIdentifier:CellIdentifier,返回cell1。cell1加入到visiableCells,cell1移出reusableTableCells;cell2移出visiableCells,cell2加入到reusableTableCells。之后再需要顯示的Cell就可以正常重用了。
所以整個(gè)過程并不難理解,但需要注意正是因?yàn)檫@樣的原因:配置Cell的時(shí)候一定要注意,對(duì)取出的重用的cell做重新賦值,不要遺留老數(shù)據(jù)。
一些情況
使用過程中,我注意到,并不是只有拖動(dòng)超出屏幕的時(shí)候才會(huì)更新reusableTableCells表,還有:
1. reloadData,這種情況比較特殊。一般是部分?jǐn)?shù)據(jù)發(fā)生變化,需要重新刷新cell顯示的內(nèi)容時(shí)調(diào)用。在cellForRowAtIndexPath調(diào)用中,所有cell都是重用的。我估計(jì)reloadData調(diào)用后,把visiableCells中所有cell移入reusableTableCells,visiableCells清空。cellForRowAtIndexPath調(diào)用后,再把reuse的cell從reusableTableCells取出來,放入到visiableCells。
2. reloadRowsAtIndex,刷新指定的IndexPath。如果調(diào)用時(shí)reusableTableCells為空,那么cellForRowAtIndexPath調(diào)用后,是新創(chuàng)建cell,新的cell加入到visiableCells。老的cell移出visiableCells,加入到reusableTableCells。于是,之后的刷新就有cell做reuse了。
@import url(http://m.shnenglu.com/CuteSoft_Client/CuteEditor/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css);