Search code examples
iosparsingcelluitableview

Table View Cells showing blanks


I've got a Table View Cell in .xib. I've got a UILabel and UIImageView in the .xib.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object
{   
    SchoolsTableViewCell *cell = (SchoolsTableViewCell *) [[[NSBundle mainBundle] loadNibNamed:@"SchoolsTableViewCell" owner:self options:nil] lastObject];

    NSLog(@"Before: %@", cell.nameLabel.text);
    cell.nameLabel.text = [NSString stringWithFormat:@"Name: %@", [object objectForKey:@"name"]];
    NSLog(@"After: %@", cell.nameLabel.text);

    PFFile *file = [object objectForKey:@"logo"];
    [file getDataInBackgroundWithBlock:^(NSData *data, NSError *error)
     {
         cell.logoImageView.image = [UIImage imageWithData:data];
     }];

    return cell;
}

As you can see, I have 2 NSLog()s, printing the below:

2015-07-08 20:17:26.739 o [1871:108786] Before: (null)

2015-07-08 20:17:26.740 o [1871:108786] After: Name: SMSAS

That is expected.

However, on my Simulator, I can only see a blank cell with Name:. It should show SMSAS in the label, and load a logo, but it's not happening. I can pass the object to the next View Controller when the cell is tapped, and it can show in that View Controller.

This is my .m for the cell.

@implementation SchoolsTableViewCell

- (void)awakeFromNib
{
    [super awakeFromNib];

    self.nameLabel = [[UILabel alloc] init];
    self.logoImageView = [[UIImageView alloc] init];

    [self.contentView addSubview:self.nameLabel];
    [self.contentView addSubview:self.logoImageView];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];
}

@end

I'm sure it's a simple mistake. Anyone care to open my eyes? Thanks!


Solution

  • Use dequeueReusableCellWithIdentifier

    static NSString * CellIdentifier = @"SchoolsTableViewCell";
    SchoolsTableViewCell *cell = (SchoolsTableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SchoolsTableViewCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }