Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dequeueReusableCellWithIdentifier always returns nil (not using storyboard)

I am creating the cell programatically using the reuse identifier.

Note - I am not using storyboard for creating the cell

Whenever the cell is dequeued, the cell is nil, so the cell needs to be newly created using alloc, which is expensive.

EDIT (added 1 more question and corrected code)

Question

  • Why does this dequeue always return nil ? How can I correct it ?
  • Does dequeue work only when used along with storyboard / nib file ?

Code

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

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if(!cell) //Every time cell is nil, dequeue not working 
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

    }

    return cell;
}
like image 681
user1046037 Avatar asked Nov 14 '12 13:11

user1046037


1 Answers

You need to first set the CellIdentifier as Cell. Are you doing that? When you are creating a new cell you need to assign this identifier Cell to it. only then iOS will be able to dequeueReusableCellWithIdentifier with that identifier. Programatically you can do it like so -

UITableViewCell *cell = [[UItableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"Cell"];

You can set identifier from Interface Builder too -

enter image description here

like image 182
Srikar Appalaraju Avatar answered Oct 26 '22 13:10

Srikar Appalaraju