ios应用程序在创建UITableView的时候会只在当前视图中创建部分cell,这是apple已经为开发者优化的一部分。
然而,在拖动的时候就会重复调用方法 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
一半的做法都是在这个方法中alloc一个新的cell出来然后再从数据源拉取数据并显示,但是在数据较为庞大的时候就会不断向机器申请内存,严重时会影响用户体验
优化思路:
在屏幕中移除cell的时候将cell放入到缓冲池中,在即将出现cell的时候将缓冲池中cell取出来,重新从数据源申请数据即可。
代码实现:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//从缓存池中取出标识为cell1的cell
//这样可以避免重新申请内存去创建UITableViewCell
static NSString *cellIdentifier = @"cell1";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier ];
if(cell == nil){
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
// UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
cell.textLabel.text = [NSString stringWithFormat:@"%ld",(long) indexPath.row];
return cell;
}