从cellForRowAtIndexPath 看cell的重用机制

  今天突然发现一个问题,由于对UITableViewCell 的重用机制不是很了解,让我纠结很久;

用过reloadData时候,会调用cellForRowAtIndexPath方法,但是请看以下2种cellForRowAtIndexPath 的写法:

 

写法A:

 1 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
 2 {
 3     static NSString *brand_region_Cell = @"MyCell";
 4     
 5     UITableViewCell *celll = [region_table dequeueReusableCellWithIdentifier:MyCell];
 6     
 7     if (cell == nil)
 8     {
 9         cell = [[UITableViewCell alloc] initWithStyle:
10                       UITableViewCellStyleDefault reuseIdentifier:@"MyCell" ];
11         
12         cell.selectionStyle = UITableViewCellSelectionStyleNone;
13     Obj *obj = [objs objectAtIndex:indexPath.row]; 
14    cell.textLabel.text = obj.obj_name;
      }

    return celll;
  }

 

写法B:

 1 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
 2 {
 3     static NSString *brand_region_Cell = @"brand_region_Cell";
 4     
 5     UITableViewCell *cell = [region_table dequeueReusableCellWithIdentifier:MyCell];
 6     
 7     if (cell == nil)
 8     {
 9     cell = [[UITableViewCell alloc] initWithStyle:
10                       UITableViewCellStyleDefault reuseIdentifier:@"MyCell" ];
11         
12         cell.selectionStyle = UITableViewCellSelectionStyleNone;
13         
14     }
15     
16     Obj *obj = [objs objectAtIndex:indexPath.row];
17     cell.textLabel.text = obj.obj_name;
18     
19     return cell;
20     
21 }

 

  大家觉得这两种写法有什么不同吗?

  其实,在创建tableView时候,cellForRowAtIndexPath根据section的数量被调用, 在执行reloadData也会调用cellForRowAtIndexPath但是,cell已经存在了,故if (cell == nil){}里面的代码不会执行,reloadData方法,顾名思义,就是刷新cell的data的,所以cell的data写在cell判空外面,这是俺犯的一个错误,不知道理解的对不对,欢迎指点~ 

 

 

转载于:https://www.cnblogs.com/A--G/p/4540919.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值