UITableViewCell not equal to null

限于喜欢 提交于 2020-01-14 14:27:33

问题


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];
      } ....


回答1:


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"



来源:https://stackoverflow.com/questions/18875759/uitableviewcell-not-equal-to-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!