Michael O'Rourke
Michael O'Rourke

Reputation: 85

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;

Upvotes: 1

Views: 421

Answers (2)

AdamPro13
AdamPro13

Reputation: 7400

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
  }
}

Upvotes: 2

Ketan Parmar
Ketan Parmar

Reputation: 27438

Refer apple documentation,

awakeFromNib,

Prepares the receiver for service after it has been loaded from an Interface Builder archive, or nib file.

so, for cell it's got called first. and cellForRowAtIndexPath calls after that and every time when you scroll your tableView it's deque the cell for reusability but this method call after awakeFromNib. so you are not getting your post object aas nil in awakeFromNib.

Upvotes: 0

Related Questions