方法1
摘自 http://www.cocoachina.com/cms/wap.php?action=article&id=15770
UITableView通過重用單元格來達到節(jié)省內(nèi)存的目的,通過為每個單元格指定一個重用標示(reuseidentifier),即指定了單元格的種類,以及當單元格滾出屏幕時,允許恢復單元格以便復用。對于不同種類的單元格使用不同的ID,對于簡單的表格,一個標示符就夠了。
如一個TableView中有10個單元格,但屏幕最多顯示4個,實際上iPhone只為其分配4個單元格的內(nèi)存,沒有分配10個,當滾動單元格時,屏幕內(nèi)顯示的單元格重復使用這4個內(nèi)存。實際上分配的cell的個數(shù)為屏幕最大顯示數(shù),當有新的cell進入屏幕時,會隨機調(diào)用已經(jīng)滾出屏幕的Cell所占的內(nèi)存,這就是Cell的重用。
對于多變的自定義Cell,這種重用機制會導致內(nèi)容出錯,為解決這種出錯的方法,把原來的
UITableViewCell *cell = [tableview dequeueReusableCellWithIdentifier:defineString]
修改為:UITableViewCell *cell = [tableview cellForRowAtIndexPath:indexPath];
不過這樣會浪費一些空間
以下兩個方法摘自http://blog.csdn.net/pilqc2009/article/details/46505357
方法2
以indexPath來作為每一行cell的標識符
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%d%d", [indexPath section], [indexPath row]];//以indexPath來唯一確定cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; //出列可重用的cell
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
//...其他代碼
}
這個方法我用在一個場景, 每行cell里面包含有不定數(shù)量的相同view, 所以只能等到model賦值才去根據(jù)接口創(chuàng)建多少個, 并規(guī)定尺寸, 所以暫時采取這種方法, 顯示是沒啥問題, 不會發(fā)生重用
方法3
清空cell上所有子視圖
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; //出列可重用的cell
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
else
{
//刪除cell的所有子視圖
while ([cell.contentView.subviews lastObject] != nil)
{
[(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];
}
}
//...其他代碼
}