zoukankan      html  css  js  c++  java
  • 从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判空外面,这是俺犯的一个错误,不知道理解的对不对,欢迎指点~ 

     

  • 相关阅读:
    驱动
    设备编号
    makefile 中的赋值
    UART
    c 语言的复杂声明
    linux下arm汇编的常用指令解析
    linux下的arm汇编程序
    ok6410下的uboot分析与实现
    层级选择器的理解
    css外部样式的理解
  • 原文地址:https://www.cnblogs.com/A--G/p/4540919.html
Copyright © 2011-2022 走看看