从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