Ran94
Ran94

Reputation: 139

Prototype cell labels showing nil in Table View Controller

I am using storyboards for creating a tableview and using prototype cells. prototype cell contains a textlabel

TableViewController :

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

static NSString *cellIdentifier = @"Cell";



Cell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
NSLog(@"cellIdentifier = %@",cell);
if (cell == nil) {
    cell = [[Cell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    NSLog(@"cellIdentifier = %@",cell);

}
            cell.nameLabel.text = [array objectAtIndex:indexPath.row];


return cell;

cell.h

@interface Cell : UITableViewCell

@property (nonatomic,weak) IBOutlet UILabel* nameLabel;

I imported cell.h in viewcontroller.m .
I named the restorationID of prototype cell as 'Cell' and class of prototype cell as 'Cell' and linked the textlabel in prototype cell to nameLabel.

Problem is :
cell.nameLabel.text always returns nil value even though [array objectAtIndex:indexPath.row] returns a string.

Upvotes: 2

Views: 258

Answers (3)

zy.liu
zy.liu

Reputation: 346

You should set cell's ReuseIdentifier instead of RestorationID. I'm curious that you didn't set ReuseIdentifier and got no crash :)

By the way, If you use a custom cell with xib, you should always register it to UITableView instance in viewDidLoad:

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.tableView registerNib:[UINib nibWithNibName:@"Cell" bundle:nil] forCellReuseIdentifier:@"Cell"];
}

Upvotes: 0

Massimo Polimeni
Massimo Polimeni

Reputation: 4906

Make sure to have done this steps:

  1. Define a new class for your custom cell, must be UITableViewCell type
  2. Add an IBOutlet property for your label in the custom cell class
  3. Establish a connection between the outlet property and the label
  4. Set the class type of your custom cell by selecting the prototype cell and go in the Identity Inspector
  5. Change the code to reference your custom cell type instead of UITableViewCell

In addition, you should use CellIdentifier instead of RestorationID.

Upvotes: 1

Teja Nandamuri
Teja Nandamuri

Reputation: 11201

Try naming the CellIdentifier instead of restorationID.

CellIdentifier is a way to tag tableViewCells. This is so that uitableView can know which uitableviewcell to pull out when it needs to reuse it.

Upvotes: 4

Related Questions