方法1 :
將獲得cell的方法從
- (UITableViewCell*)dequeueReusableCellWithIdentifier:(NSString*)identifier 換為-(UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath
重用機制調(diào)用的就是dequeueReusableCellWithIdentifier這個方法鸦概,方法的意思就是“出列可重用的cell”洼哎,因而只要將它換為cellForRowAtIndexPath(只從要更新的cell的那一行取出cell)丽声,就可以不使用重用機制棉磨,因而問題就可以得到解決丽惶,雖然可能會浪費一些空間缅阳。
//下面是示例代碼:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
// UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; //改為以下的方法
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; //根據(jù)indexPath準確地取出一行,而不是從cell重用隊列中取出
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}......
上面的代碼音羞,無疑是能夠解決界面錯亂的問題囱桨,但如果數(shù)據(jù)很多,那就會浪費相當多的空間嗅绰,不推薦使用舍肠。
方法2:
為每個cell指定不同的重用標識符(reuseIdentifier)來解決。
重用機制是根據(jù)相同的標識符來重用cell的窘面,標識符不同的cell不能彼此重用翠语。于是我們將每個cell的標識符都設(shè)置為不同,就可以避免不同cell重用的問題了财边。
怎么為每個cell都設(shè)置不同的標示符呢肌括?其實很簡單 在返回每一行cell的數(shù)據(jù)源方法中 通過為每一個cell的標示符綁定indexPath.section--indexPath.row就可以了,下面是示例代碼:
//實現(xiàn)建立cell的具體內(nèi)容
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString * ID = [NSString stringWithFormat:@"cell-ld%-ld%",[indexPath section ],[indexPath row]];
//2.到緩存池中去查找可重用標示符
HMWeiboCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];
if (cell == nil) {
cell = [[HMWeiboCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
}
//給cell中得屬性framemodel賦值
HMWeiboFrameModel * frameModel = self.weiboFrameArray[indexPath.row];
cell.weiboFrameModel = frameModel;
return cell酣难;
}
//上面的這種方式 雖然說比第一種方式有了一定的改進谍夭,通過為每一個cell都綁定了一個不同的標識符能夠使得cell與cell之間不會重用,解決了界面錯亂的問題憨募,但是從根本上來說還是沒有太大的內(nèi)存優(yōu)化紧索,同樣的如果數(shù)據(jù)比較多還是比較浪費空間。
方法3:
第三種方式其實很簡單就是刪除重用cell的所有子視圖菜谣,這句話什么意思呢珠漂?當我們從緩存池中取得重用的cell后,通過刪除重用的cell的所有子視圖尾膊,從而得到一個沒有特殊格式的cell媳危,供其他cell重用。是不是還是沒懂什么意思冈敛,那我們就接著來看代碼:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *ID = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID]; //出列可重用的cell
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
}
else
{
//刪除cell的所有子視圖
while ([cell.contentView.subviews lastObject] != nil)
{
[(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];//強制裝換為UIView類型 待笑,移除所有子視圖
}
}
return cell;
}