iosobjective-cdata-objects

Handling Data Object in UITableViewCell


I would like to move everything in between the two lines into detailCell.m so that the only code in cellForRowAtIndexPath are the remaining three lines. What is the most effective way to do this? Thank you.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DetailCell" forIndexPath:indexPath];
    Job *aJob = self.jobs[indexPath.row];

 _______________
    [cell.titleLabel setText:aJob.title];
    [cell.companyLabel setText:aJob.company];

    if (aJob.logo != (NSString *)[NSNull null]) {
        [cell.logoImageView setImageWithURL:[NSURL URLWithString:aJob.logo] placeholderImage:[UIImage imageNamed:@"placeholder.jpg"]];
    }
    else {
        [cell.logoImageView setImage:[UIImage imageNamed:@"placeholder.jpg"]];
    }
_________________
    return cell;
}

Here is DetailCell.h. DetailCell.m is currently empty.

@interface DetailCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UILabel *companyLabel;
@property (weak, nonatomic) IBOutlet UIImageView *logoImageView;
@end

Solution

  • Create a method in DetailCell.h something like:

    - (void)configureCell:(Job *)aJob atIndexPath:(NSIndexPath *)indexPath;
    

    And implement it in DetailCell.m as you like it:

    - (void)configureCell:(Job *)aJob atIndexPath:(NSIndexPath *)indexPath {
      [self.titleLabel setText:aJob.title];
      [self.companyLabel setText:aJob.company];
    
      if (aJob.logo != (NSString *)[NSNull null]) {
        [self.logoImageView setImageWithURL:[NSURL URLWithString:aJob.logo] placeholderImage:[UIImage imageNamed:@"placeholder.jpg"]];
      } else {
        [self.logoImageView setImage:[UIImage imageNamed:@"placeholder.jpg"]];
      }
    }
    

    That's about it... When you do that all you need to do in your cellForRowAtIndexPath method is:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
      DetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DetailCell" forIndexPath:indexPath];
      Job *aJob = self.jobs[indexPath.row];
      [cell configureCell:aJob atIndexPath: indexPath];
      return cell;
    }
    

    You actually don't need indexPatin in that cell method, but i have a habit of passing it always to the cell as it's usually a good thing to have it available :)