Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 205
Allen Avatar asked Jul 10 '26 02:07

Allen


1 Answers

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"

like image 138
rdelmar Avatar answered Jul 14 '26 15:07

rdelmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!