Allen
Allen

Reputation: 3771

UITableViewCell not equal to null

I'm having trouble with the following code below, which basically is instantiating an extend uitableviewcell from a storyboard. The problem I'm having is that it seems leftMenuCell is never equal to null, and thus never enters the initiating block. What am I doing wrong?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
      static NSString *CellIdentifier = @"LeftMenuCell";
      MenuCell *leftMenuCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

      if(leftMenuCell == nil) {
          NSLog(@"creating a new cell");
          leftMenuCell = [[MenuCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
      } ....

enter image description here

Upvotes: 3

Views: 738

Answers (1)

rdelmar
rdelmar

Reputation: 104082

You're not doing anything wrong, that's just the way table views work when you make the cell in the storyboard. The method dequeueReusableCellWithIdentifier:, always returns a valid cell when that cell is in a table view in a storyboard. It seems that many programmers haven't figured this out, and still include the if cell==nil clause. This is from the docs:

"If the dequeueReusableCellWithIdentifier: method asks for a cell that’s defined in a storyboard, the method always returns a valid cell. If there is not a recycled cell waiting to be reused, the method creates a new one using the information in the storyboard itself. This eliminates the need to check the return value for nil and create a cell manually"

Upvotes: 9

Related Questions