2011년 11월 3일 목요일

Cell Reuse Identifier

If you created a custom cell, define the cell reuse identifier in the cell implementation file. To do that, write a +(id)cell; and +(id)cellForTableView:(UITableView*)tableView;

  1. #define kCustomCellIdentifier @"customCellId"
  2.  
  3. @implementation CustomCell
  4.  
  5. + (id)cell {
  6.     CustomCell *cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:kCustomCellIdentifier];
  7.     return cell;
  8. }
  9. + (id)cellForTableView:(UITableView *)tableView
  10. {
  11.     CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:kCustomCellIdentifier];
  12.     if (!cell) {
  13.         cell = [self cell];
  14.     }
  15.     return cell;
  16. }
  17. // ...
  18.  

You can call the above code like this:

  1. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  2. {
  3.     CustomCell *cell = [CustomCell cellForTableView:tableView];
  4.     // ...

This is useful to simplify the tableView dataSource codes.