总结 ﹣ UITableView (性能优化①)

[color=red]注 : 文章不断更新,转载文章请加上作者 [/color]

[url=http://cwlong.iteye.com/admin/blogs/2230371] 总结 ﹣ UITableView [/url] 中,说了如何遵守协议调用方法,使UITableView展示数据: 如下面代码所示


//这种调用方法,固然可以从数据模型中获取到数据,并且展示出来,
//每当一个cell进入视野范围内,就会调用一次方法(打印一下就可以测试)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:nil];

Apple *apple = self.apple[indexPath.row];

cell.textLabel.text =apple.name;

cell.detailTextLabel.text = apple.intro;

cell.imageView.image = [UIImage imageNamed:apple.icon];

return cell;
}



[size=medium][color=red]不好的地方:(对性能的影响)[/color][/size]
1 . 一开始就创建了可视范围的多个对象
2 . 每调用一次都分配[color=red]新的[/color]存储空间,去创建UITableViewCell对象 , 也就是说, 假如滚动很快,快速来回滚动的时候,内存会忽然飙升得很高.(因为不断[[UITableViewCell alloc] )


[size=medium][u]性能优化 : [/u][/size]

性能优化的思路 :

假如屏幕只能显示[color=red]八块UITableViewCell [/color], 引入一个[b][color=red]缓存池机制 [/color][/b],当继续滚动到下一个的时候 , 这个时候创建[color=red]第九块 UITableViewCell[/color] , 然后[color=red]第一块UITableViewCell[/color]完全消失的时候,将它放入[b][color=red]缓存池 [/color][/b]中,等到[color=red]第十块UITableViewCell[/color]需要再创建的时候,从[b][color=red]缓存池 [/color][/b]中拿出[color=red]第一块UITableViewCell[/color] , 周而复始.

[u][i][b][color=red]所以. 屏幕假如只显示8块Cell , 整个过程至销毁只要创建9块Cell对象即可.整个过程怎样滚动也不需要在多创建UITableViewCell[/color][/b][/i][/u]

[color=blue]注意点:[/color]
[color=blue] 当开发程序复杂的时候,[/color][b][color=red]缓存池 [/color][/b][color=blue]里面有各种各样的东西,很多的cell等,所以怎样知道区分cell对应的UITableView呢?[/color]

解决办法: 每次创建UITableViewCell , 都给它绑定一种类型(一种标示等) , 然后从[b][color=red]缓存池 [/color][/b][color=blue][/color]中找的时候,根据类型(标示等)去找到对应的
cell用来重用

步骤:
1. 通过一个标识,去缓存池中寻找可循环利用的cell
2. 如果缓存池找不到, 可循环利用的cell: 创建一个新的cell , 给cell贴个标识
3. 给cell设置新的数据.

代码如下 :



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//0. static修饰局部变量: 可以保证局部变量只分配以此存储空间(只初始化一次)
static NSString *ID = @"Apple";

//1. 通过一个标识,去缓存池中寻找可循环利用的cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];

//2. 如果缓存池找不到, 可循环利用的cell: 创建一个新的cell , 给cell贴个标识
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
}

//3 经过前两步后肯定又Cell了.给cell设置新的数据.
Apple *apple= self.apple[indexPath.row];

cell.textLabel.text =apple.name;

cell.detailTextLabel.text = apple.intro;

cell.imageView.image = [UIImage imageNamed:apple.icon];


NSLog(@"%p - %@ - %ld ",cell,apple.name,indexPath.row);

return cell;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值