UITableView展示数据的内存优化

2018-12-10  本文已影响0人  丹丹十个胆小鬼

1、优化思路

首先会根据ID这个标识去缓存池取可循环利用的cell;如果缓存池中没有可循环利用的cell,会判断有没有根据ID这个标识注册对应的cell类型,如果有注册,会自动创建这种类型的cell,并且绑定ID这个标识返回,如果没有注册,会去SB中查找,如果没有,需要手动创建cell。

2、代码实现

- (void)viewDidLoad {
    [super viewDidLoad];
    // 根据ID这个标识注册对应的cell类型为UITableViewCell
    // 只需要注册一次,不能放在这个代理方法中,一般都是放在viewDidLoad方法中
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:carID];
}

#pragma mark -dataSource方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.carGrounps.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    FLCarGrounp *carGroup = self.carGrounps[section];
    return carGroup.carsArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 根据ID这个标识注册对应的cell类型为UITableViewCell
    // 只需要注册一次,不能放在这个代理方法中,一般都是放在viewDidLoad方法中
//    [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:carID];
    // 先从缓存器中取cell
    // dequeueReusableCellWithIdentifier这个方法内部首先会根据ID这个标识去缓存池取可循环利用的cell;如果缓存池中没有可循环利用的cell,会判断有没有根据ID这个标识注册对应的cell类型,如果有注册,会自动创建这种类型的cell,并且绑定ID这个标识返回
    // 特点:不能设置cell的类型
    // 场景:自定义cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:carID];
    // 缓存器中没有cell,就直接创建
//    if (cell == nil) {
//        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:carID];
//        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
//     }
    NSLog(@"cell:%p", cell);
    FLCarGrounp *carGrounp = self.carGrounps[indexPath.section];
    FLCar *car = carGrounp.carsArray[indexPath.row];
    cell.imageView.image = [UIImage imageNamed:car.icon];
    cell.textLabel.text = car.name;
    
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    FLCarGrounp *carGroup = self.carGrounps[section];
    return carGroup.header;
}

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
    
    FLCarGrounp *carGroup = self.carGrounps[section];
    return carGroup.footer;
}

#pragma mark UITableviewDelegate方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    FLCarGrounp *carGroup = self.carGrounps[indexPath.section];
    FLCar *car = carGroup.carsArray[indexPath.row];
    NSLog(@"选中了%@", car.name);
}
上一篇 下一篇

猜你喜欢

热点阅读