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判空外面,这是俺犯的一个错误,不知道理解的对不对,欢迎指点~ 

     

  • 相关阅读:
    Android虚拟、实体键盘不能同时使用?
    libwebsockets 运行问题
    Qt TabWidget QTabBar 宽高设置
    I.MX6 recovery mode hacking
    libwebsockets libwebsockets-webserver.c hacking
    MySQL(六)常用语法和数据类型
    MySQL(五)汇总和分组数据
    MySQL(四)字段及常用函数
    MySQL(三)用正则表达式搜索
    MySQL(二)数据的检索和过滤
  • 原文地址:https://www.cnblogs.com/A--G/p/4540919.html
Copyright © 2011-2022 走看看