iOS UITableViewCell 重用及 性能优化

UITableViewCell重用

  • 基本的重用方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 0 重用标识
    // 被static修饰的局部变量,只会出初始化一次,在整个程序运行尘中,只有一分内存
    static NSString *ID = @"cell";

    // 1. 先根据cell的标识去缓存池中查找可循环利用cell
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];

    // 2. 如果cell为nil(缓存池找不到对应的cell)
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }

    // 3.覆盖数据
    cell.textLabel.text = [NSString stringWithFormat:@"test - %zd",indexPath.row];

    return cell;
}
  • cell优化

    • 在viewController项目中创建一个继承UITableViewController的类,然后在storyboard托一个UITableViewController之后修改cell标识 就可以了.
  • 代码案例

#import "ZJTestViewController.h"

@interface ZJTestViewController ()

@end

@implementation ZJTestViewController

- (void)viewDidLoad {
    [super viewDidLoad];


}


#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 20;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 0 重用标识
    // 被static修饰的局部变量,只会出初始化一次,在整个程序运行尘中,只有一分内存
    static NSString *ID = @"cell";

    // 1. 先根据cell的标识去缓存池中查找可循环利用cell
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];

    // 如果在storyboard中设置了 标识,即便是第一次为空 也不需要再次创建了, 因为他会默认首先在storyboard中找cell的标识. 因为我在storyboard中设置了cell标识,所以这里不需要在进行判断.
//    // 2. 如果cell为nil(缓存池找不到对应的cell)
//    if (cell == nil) {
//        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
//    }
//    
    // 3.覆盖数据
    cell.textLabel.text = [NSString stringWithFormat:@"test - %zd",indexPath.row];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //...
}
// 当然cell重用的写法还有很多,如果想减少这个方法中的代码,我们也可以另写一个方法,然后传递参数就可以实现,具体用法,以后会在项目中进行操作

尽情期待后期更新…

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值