Michael O'Rourke Michael O'Rourke - 2 months ago 7
iOS Question

Initialize custom UITableViewCell with custom object

I have a

Post
object I am trying to initialize a
PostTableViewCell
with. Below is what I am doing in my view controller -

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *identifier = @"Post";
Post *post = [self.posts objectAtIndex:indexPath.row];
PostTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:identifier];

cell.post = post;

return cell;
}


In
cellForRow
the object comes instantiated with all the correct data. Why is
Post
property nil in
PostTableViewCell.h
while
awakeFromNib
executes?

In the
PostTableViewCell.h
I have -

@property (strong, nonatomic) Post *post;

Answer

The reason post is nil when awakeFromNib is called is because that property is not yet set. The UITableView handles instantiation of the table view cell, which happens sometime before you call dequeueReusableCellWithIdentifier:. You are setting the post property on the cell after cell instantiation.

What you want to do instead is override the method -(void)setPost:(Post *)post in PostTableViewCell.m. This is the setter for the property that automatically gets called when you set the property.

- (void)setPost:(Post *)post {
  if (post != _post) {
    _post = post;
    [self updateCellAppearance]; // Your own method that updates the cell's data and appearance as needed
  }
}